计算器例子:
public class Command : ICommand { private Queue<decimal> queue = new Queue<decimal>(); public decimal[] GetResults=>queue.ToArray(); private Receiver _receiver; public Receiver Receiver { get => _receiver; set => _receiver=value; } public decimal Execute(params decimal[] items) { var result = _receiver.Cal(items); queue.Enqueue(result); return result; } public decimal Reset() { return queue.Dequeue(); } } public class Add : Receiver { public decimal Cal(params decimal[] items) { return items.Aggregate((x, y) => x + y); } } public class Sub : Receiver { public decimal Cal(params decimal[] items) { return items.Aggregate((x, y) => x - y); } } public class Mul : Receiver { public decimal Cal(params decimal[] items) { return items.Aggregate((x, y) => x * y); } } public class Div : Receiver { public decimal Cal(params decimal[] items) { return items.Aggregate((x, y) => x/ y); } } public interface Receiver { decimal Cal(params decimal[] items); } public interface ICommand { decimal Execute(params decimal[] items); Receiver Receiver { get; set; } } public interface IClient { decimal Execute(params decimal[] items); decimal Reset(); } public class Client:IClient { private Queue<decimal> queue = new Queue<decimal>(); private ICommand _command; public Client(ICommand command) { _command = command; } public decimal Execute(params decimal[] items) { decimal result = _command.Execute(items); queue.Enqueue(result); return result; } public decimal Reset() { return queue.Dequeue(); } }
客户端实现:
Command addCommand = new Command(); addCommand.Receiver = new Add(); IClient client = new Client(addCommand); var result = client.Execute(1, 2, 3, 4, 5); result = client.Reset(); Command subCommand = new Command(); subCommand.Receiver = new Sub();
标签:items,decimal,模式,命令,params,result,Receiver,public From: https://www.cnblogs.com/morec/p/16910849.html