Skip to content

Instantly share code, notes, and snippets.

@miteshsureja
Created May 1, 2017 12:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miteshsureja/9efcb3011547b89bbebd6aba96787b70 to your computer and use it in GitHub Desktop.
Save miteshsureja/9efcb3011547b89bbebd6aba96787b70 to your computer and use it in GitHub Desktop.
Command Pattern
//Concrete Command class
public class BuyCommand : ICommand
{
private Product Product;
public string Name
{
get
{
return "Buy Command";
}
}
public BuyCommand(Product product)
{
Product = product;
}
public void Execute()
{
Console.WriteLine("Executing {0}", Name);
Product.Buy();
}
}
//Command interface
public interface ICommand
{
void Execute();
string Name { get; }
}
//Invoker class
public class Portal
{
public string PortalName { get; set; }
public Portal(string name)
{
PortalName = name;
}
public List<ICommand> orderList = new List<ICommand>();
public void AddOrder(ICommand cmd)
{
orderList.Add(cmd);
}
public void ExecuteOrder()
{
Console.WriteLine("Executing all orders from {0}", PortalName);
foreach(var order in orderList)
{
order.Execute();
}
}
}
//Receiver class
public class Product
{
public int Quantity { get; set; }
public string Name { get; set; }
public Product(string prodName, int qty)
{
Name = prodName;
Quantity = qty;
}
public void Buy()
{
Console.WriteLine("Purchased {0} quantities of {1}", Quantity, Name);
}
public void Sell()
{
Console.WriteLine("Sold {0} quantities of {1}", Quantity, Name);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CommandPattern
{
//Client class
class Program
{
static void Main(string[] args)
{
Product laptop = new Product("Laptop", 2);
BuyCommand buyLaptop = new BuyCommand(laptop);
SellCommand sellLaptop = new SellCommand(laptop);
Portal portal = new Portal("Amazon.in");
portal.AddOrder(buyLaptop);
portal.AddOrder(sellLaptop);
portal.ExecuteOrder();
Console.ReadLine();
}
}
}
//Concrete Command class
public class SellCommand : ICommand
{
private Product Product;
public string Name
{
get
{
return "Sell Command";
}
}
public SellCommand(Product product)
{
Product = product;
}
public void Execute()
{
Console.WriteLine("Executing {0}", Name);
Product.Sell();
}
}
@miteshsureja
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment