命令模式(Command Pattern)
命令模式是一种数据驱动的设计模式,属于行为型模式类别。请求被包装在一个对象中作为命令,并传递给调用对象。调用对象寻找可以处理该命令的合适对象,并将命令传递给相应的对象,该对象执行命令。
实现
-
步骤 1:创建一个命令接口。文章来源:https://www.toymoban.com/news/detail-632018.html
public interface IOrder { void Execute(); }
-
步骤 2:创建一个请求类。文章来源地址https://www.toymoban.com/news/detail-632018.html
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
到了这里,关于C#设计模式(15)命令模式(Command Pattern)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!