标签:
1 public class Program 2 { 3 public static void Main(string[] args) 4 { 5 Light light=new Light("light0001"); 6 // light turn on. 7 light.On(); 8 // light turn off. 9 light.Off(); 10 } 11 } 12 13 public class Light 14 { 15 public string Name { get; set; } 16 17 public Light(string name) 18 { 19 this.Name = name; 20 } 21 22 /// <summary> 23 /// Turn on the light 24 /// </summary> 25 public void On() 26 { 27 Console.WriteLine("light:{0} is turn on.", this.Name); 28 } 29 30 /// <summary> 31 /// Turn off the light 32 /// </summary> 33 public void Off() 34 { 35 Console.WriteLine("light:{0} is turn off.", this.Name); 36 } 37 }
试想,如果把FTP服务器端,接收到的命令拆分成不同的“命令”,有单一的“命令调用者”,这样会不会把结构划分的更清晰?
备注:FTP向服务端请求命令:LS、DIR、MLS、MDIR、MKDIR、RMDIRLS有点像UNIX下的LS(LIST)命令:DIR相当于LS-L(LIST-LONG);MLS只是将远端某目 录下的文件存于LOCAL端的某文件里;MDIR相当于MLS;MKDIR像DOS下的MD(创建子目录)一样:RMDIR像DOS下的RD(删除子目录)一样。
1 public interface ICommand 2 { 3 4 void Execute(); 5 6 }
1 public class Light 2 { 3 public string Name { get; set; } 4 5 public Light(string name) 6 { 7 this.Name = name; 8 } 9 10 /// <summary> 11 /// Turn on the light 12 /// </summary> 13 public void On() 14 { 15 Console.WriteLine("light:{0} is turn on.", this.Name); 16 } 17 18 /// <summary> 19 /// Turn off the light 20 /// </summary> 21 public void Off() 22 { 23 Console.WriteLine("light:{0} is turn off.", this.Name); 24 } 25 }
1 public class LightOnCommand : ICommand 2 { 3 private Light light; 4 5 public LightOnCommand(Light light) 6 { 7 this.light = light; 8 } 9 10 public void Execute() 11 { 12 this.light.On(); 13 } 14 }
1 public class LightOffCommand : ICommand 2 { 3 private Light light; 4 5 public LightOffCommand(Light light) 6 { 7 this.light = light; 8 } 9 10 public void Execute() 11 { 12 this.light.Off(); 13 } 14 }
1 public class CommandControl 2 { 3 private ICommand command; 4 5 public CommandControl() { } 6 7 public void SetCommand(ICommand command) 8 { 9 this.command = command; 10 } 11 12 public void ButtonPresssed() 13 { 14 this.command.Execute(); 15 } 16 }
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 CommandControl control = new CommandControl(); 6 Light light = new Light("light_001"); 7 LightOnCommand lightOn = new LightOnCommand(light); 8 LightOffCommand lightOff = new LightOffCommand(light); 9 10 control.SetCommand(lightOn); 11 control.ButtonPresssed(); 12 13 control.SetCommand(lightOff); 14 control.ButtonPresssed(); 15 16 control.SetCommand(lightOn); 17 control.ButtonPresssed(); 18 19 control.SetCommand(lightOff); 20 control.ButtonPresssed(); 21 22 Console.ReadKey(); 23 } 24 }
标签:
原文地址:http://www.cnblogs.com/yy3b2007com/p/4630802.html