C# 设计模式(16)命令模式
命令模式
1. 实现异步队列
2.数据恢复,命令撤销
代码实现:
对象:
namespace CommandPattern { public class Document { public int Id { get; set; } public string Name { get; set; } } }
行为:
public abstract class BaseCommand { protected Document Document =null; protected Receiver Receiver = null; public void SetDocument(Document document) { this.Document = document; } public void SetReceiver(Receiver receiver) { this.Receiver = receiver; } public abstract void Execute(); } public class ReadCommand : BaseCommand { public override void Execute() { Receiver.Name = Document.Name; Receiver.Read(); } } class WriteCommand:BaseCommand { public override void Execute() { Receiver.Name = Document.Name; Receiver.Write(); } }
执行者:
public class Receiver { public string Name { get; set; } public void Write() { Console.WriteLine($"{Name} Write Data..."); } public void Read() { Console.WriteLine($"{Name} Read Data..."); } }
代码调用:
class Program { static void Main(string[] args) { Document doc = new Document() { Id=01, Name = "Action1" }; while (true) { Console.WriteLine("Please Insert Command W or R"); string input = Console.ReadLine(); var instance = ConfigurationManager.AppSettings[input].Split(',')[1]; var method = ConfigurationManager.AppSettings[input].Split(',')[0]; BaseCommand cmd = (BaseCommand) Activator.CreateInstance(instance, method).Unwrap(); Receiver receiver = new Receiver(); cmd.SetReceiver(receiver); cmd.SetDocument(doc); cmd.Execute(); } } }
结果: