Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment