应用场景:将行为请求者与行为执行者解耦。
using System; using System.Collections.Generic; using System.Text; namespace CommandTest { class Program { static void Main(string[] args) { //实际开发中,还可以把各命令加入队列中,并支持撤销(Undo)操作和恢复(Redo)操作。 Receiver receiver = new Receiver(); ICommand cmd1 = new Command1(receiver); ICommand cmd2 = new Command2(receiver); cmd1.Execute(); cmd2.Execute(); Console.Read(); } } public interface ICommand { void Execute(); } public class Command1 : ICommand { private Receiver receiver; public Command1(Receiver receiver) { this.receiver = receiver; } public void Execute() { receiver.Show1(); } } public class Command2 : ICommand { private Receiver receiver; public Command2(Receiver receiver) { this.receiver = receiver; } public void Execute() { receiver.Show2(); } } //命令接收者 public class Receiver { public void Show1() { } public void Show2() { } } }