close
This tutorial is about command pattern, which is my thoghts after watching the tutorial created by Christopher Okhravi.
Receiver portion:
1: public class Light
2: {3: //Action: On/Off
4: public void On()
5: {6: Console.WriteLine("Turn on the light.");
7: }8: public void Off()
9: {10: Console.WriteLine("Turn off the light.");
11: }12: public void Up()
13: {14: Console.WriteLine("Open the door");
15: }16: public void Down()
17: {18: Console.WriteLine("Close the door");
19: } 20: }ICommand portion:
1: namespace CommandPattern
2: {3: interface ICommand
4: {5: void Execute();
6: void Unexecute();
7: } 8: }LightOnCommand portion:
1: 2: class LightOnCommand : ICommand
3: { 4: Light light;5: public LightOnCommand(Light _light)
6: {7: this.light = _light;
8: }9: public void Execute()
10: {11: this.light.On();
12: } 13: 14: public void Unexecute()
15: {16: this.light.Off();
17: } 18: } 19: LightOffCommand portion:
1: class LightOffCommand : ICommand
2: { 3: Light light;4: public LightOffCommand(Light _light)
5: {6: this.light = _light;
7: }8: public void Execute()
9: {10: this.light.Off();
11: } 12: 13: public void Unexecute()
14: {15: this.light.On();
16: } 17: }LightUpCommand portion:
1: class LightUpCommand : ICommand
2: { 3: Light light;4: public LightUpCommand(Light _light)
5: {6: this.light = _light;
7: }8: public void Execute()
9: {10: this.light.Up();
11: } 12: 13: public void Unexecute()
14: {15: this.light.Down();
16: } 17: }LightDownCommand portion:
1: class LightDownCommand : ICommand
2: { 3: Light light;4: public LightDownCommand(Light _light)
5: {6: this.light = _light;
7: }8: public void Execute()
9: {10: this.light.Down();
11: } 12: 13: public void Unexecute()
14: {15: this.light.Up();
16: } 17: }Invoker portion:
1: class Invoker
2: {3: IList<ICommand> commands = new List<ICommand>();
4: public Invoker(ICommand cmd)
5: {6: this.commands.Add(cmd);
7: }8: public void setCommand(ICommand cmd)
9: {10: this.commands.Add(cmd);
11: }12: public void Execute()
13: {14: foreach(ICommand cmd in commands)
15: { 16: cmd.Execute(); 17: } 18: } 19: }Console portion:
1: class Program
2: {3: static void Main(string[] args)
4: {5: Light light = new Light();
6: ICommand onCmd = new LightOnCommand(light);
7: ICommand offCmd = new LightOffCommand(light);
8: ICommand upCmd = new LightUpCommand(light);
9: ICommand downCmd = new LightDownCommand(light);
10: Invoker invoker = new Invoker(onCmd);
11: invoker.setCommand(upCmd); 12: invoker.setCommand(downCmd); 13: invoker.setCommand(upCmd); 14: invoker.setCommand(upCmd); 15: invoker.setCommand(offCmd); 16: invoker.Execute(); 17: Console.ReadKey(); 18: } 19: }全站熱搜





留言列表
