命令模式(Command Pattern)
命令模式是一种数据驱动的设计模式,属于行为型模式类别。请求被包装在一个对象中作为命令,并传递给调用对象。调用对象寻找可以处理该命令的合适对象,并将命令传递给相应的对象,该对象执行命令。
实现
-
步骤 1:创建一个命令接口。
public interface IOrder {void Execute(); }
-
步骤 2:创建一个请求类。
public class Stock {private string name = "ABC";private int quantity = 10;public void Buy(){Console.WriteLine($"Stock [ Name: {name}, Quantity: {quantity} ] bought");}public void Sell(){Console.WriteLine($"Stock [ Name: {name}, Quantity: {quantity} ] sold");}
}
- 步骤 3:创建实现 IOrder 接口的具体类。
public class BuyStock : IOrder {private Stock abcStock;public BuyStock(Stock abcStock){this.abcStock = abcStock;}public void Execute() {abcStock.Buy();}
}public class SellStock : IOrder {private Stock abcStock;public SellStock(Stock abcStock){this.abcStock = abcStock;}public void Execute() {abcStock.Sell();}
}
- 步骤 4:创建命令调用类。
public class Broker {private List<IOrder> orderList = new List<IOrder>(); public void TakeOrder(IOrder order){orderList.Add(order); }public void PlaceOrders(){foreach (IOrder order in orderList) {order.Execute();}orderList.Clear();}
}
- 步骤 5:使用 Broker 类接受并执行命令。
public class CommandPatternDemo {public static void Main(string[] args) {Stock abcStock = new Stock();BuyStock buyStockOrder = new BuyStock(abcStock);SellStock sellStockOrder = new SellStock(abcStock);Broker broker = new Broker();broker.TakeOrder(buyStockOrder);broker.TakeOrder(sellStockOrder);broker.PlaceOrders();}
}
- 步骤 6:验证输出。
Stock [ Name: ABC, Quantity: 10 ] bought
Stock [ Name: ABC, Quantity: 10 ] sold