Command Pattern

From Logic Wiki
Jump to: navigation, search


Video

https://www.youtube.com/watch?v=9qA5kw8dcSU

Definition

An object is used to encapsulate all information needed to perform an action or trigger an event at a later time. This information includes the method name, the object that owns the method and values for the method parameters.

CommandPattern.png

Usage

Interface

Interface ICommand(){
   execute();
   unexecute();
}

Concrete Command

class LightOnCommand : ICommand{
  private light _light
  public Command(light l){
     _light = l;
  }
  public void execute(){
    _lights.on();
  }

}

Invoker

  class Invoker {
    ICommand _on ;
    ICommand _off ;
    ICommand _up ;
    ICommand _down; 
  public Invoker (ICommand on, ICommand off, ICommand up, ICommand down){
    _on = on;
    _off = off; 
   ...
  }
   public void ClickOn(){
   _on.execute();
   }
   public void ClickOff(){
    _off.execute();
   }
   ...
  }

Using

 new Invoker (new LightOnCommand(light), new LightOffCommand(light), new LightUpCommand(light),  new LightDownCommand(light))