Command Pattern
- Encapsulate request as an object
- Object-oriented callback
- Decouple sender from processor
- Often used for "undo" action
Design
- Object per command
- Command interface
- execute method
- undo method
- Use reflexion
Main
public static void main(String[] args) {
//Receiver - (Action)LightReceiver lc = new LightReceiver();//OnCommand = concrete commandCommand c = new OnCommand(lc);
//Invoker - (Execute)SwitchInvoker si = new SwitchInvoker();si.storeAndExecute(c);}
Receiver
public class LightReceiver {
public void on(){System.out.println("Light is on");}public void off(){System.out.println("Light is off");}}
Invoker
public class SwitchInvoker {
public void storeAndExecute( Command command){command.execute();}}
Command
public interface Command {
public void execute();}
Specific Command
public class OnCommand implements Command {
LightReceiver lg;public OnCommand(LightReceiver lg){this.lg = lg;}@Overridepublic void execute() {lg.on();}}
Adding STATE
Specific Command with State
In this case is another command but the Invoker state equals
Receiver
public class ToogleLightReceiver {
boolean isOn = false;public boolean isOn(){return isOn;}public void toogle(){if(isOn)off();elseon();isOn = !isOn;}public void on(){System.out.println("Light is on");}public void off(){System.out.println("Light is off");}}
New Command with state
public class ToggleCommand implements Command {ToogleLightReceiver lg;public ToggleCommand(ToogleLightReceiver lg){this.lg = lg;}@Overridepublic void execute() {lg.toogle();}}
Main
public static void main(String[] args) {
//ReceiverToogleLightReceiver lc = new ToogleLightReceiver();//InvokerSwitchInvoker si = new SwitchInvoker();//OnCommand = concrete commandCommand c = new ToggleCommand(lc);si.storeAndExecute(c);si.storeAndExecute(c);}
Comentarios
Publicar un comentario