Hello
We have Light devices, which can beam or not.
We do not want control directly Light source, because we want learn Command Design Pattern :-)
Of course, the reasons is others. For example, we want to be less sensitive to changes.
In implementation of Command Design Patter in our example we have 3 players:
Code behind it:
Tester:
Result:
We have Light devices, which can beam or not.
We do not want control directly Light source, because we want learn Command Design Pattern :-)
Of course, the reasons is others. For example, we want to be less sensitive to changes.
In implementation of Command Design Patter in our example we have 3 players:
- Device: is a Light which can be "ON" or "OFF" state.
- Command turn "ON" the lights: is Light "ON" command. Is a class, which wraps above Light. Heart of this class - turn "ON" the Light, which encapsulated in single function "Execute".
- Remote: some class which got command and call it "Execute". When user call "Click Remote" of this class, its method call "Execute" of command
Illustration:
public interface ICommand { void Execute(); } public class Light { public void On() { Console.WriteLine("Light is ON"); } public void Off() { Console.WriteLine("Light is OFF"); } } public class LightOnCommand : ICommand { private Light _light; public LightOnCommand(Light light) { _light = light; } public void Execute() { _light.On(); } } public class SimpleRemoteControl { ICommand _command; public void SetCommand(ICommand command) { _command = command; } public void ClickButton() { _command.Execute(); } }
Tester:
Light light = new Light(); ICommand lightOnCmd = new LightOnCommand(light); SimpleRemoteControl remote = new SimpleRemoteControl(); remote.SetCommand(lightOnCmd); remote.ClickButton();
Result:
No comments:
Post a Comment