Thursday, December 13, 2012

Command Pattern

Command Pattern :
    It is used to encapsulate request as an object and pass to an invoker, wherein the invoker
doesnot knows how the service the request but uses the encapsulated command to perform an action.

Key Terms:
Command  : It is an interfcae with excecute method . It is core of contract.
Command Implementation :its instance creates a binding between receiver and an action.
Client : Its creates an instance of Command implementation and associates with a receiver.
Invoker : It instructs command to an action.
Receiver: It knows the actual steps to perform an action.

When to use:
1. A History of requests needed.
2. Need Callback functionality.
3. Requests need to handled at varient time or varient orders.
4. A invoker should be decupled from the object handling the invocation.

Example:

Take an Example of Light process .

1. Create Command interface have execute method

public interface Command {
    public void execute();
}

2. Create Receiver Class , it's knows actual steps to perform an action

public class Light {
    boolean on;
    public void switchOn()   {
       on = true;
       System.out.println("Light is on");
   }
   public void switchOff()  {
       on = false;
       System.out.println("Light is off");
   }
}

3. Create a Command Implemention associated with receiver

// For On
public class LightOnCommand implements Command{
    // associated receiver
    Light light;
    public LightOnCommand(Light light)  {
        this.light = light;
    }
    public void execute() {
        light.switchOn();
    }
}

// Similarly for Off
public class LightOffCommand implements Command {
    // associated receiver
    Light light;
    public LightOffCommand(Light light)   {
        this.light = light;
    }
    public void execute() {
        light.switchOff();
    }
}

4. Create Inoker class ,it's instructs the command to an action

public class RemoteControl {
    private Command cmd;
    public void setCommand(Command cmd)
    {
        this.cmd = cmd;
    }
    public void pressButton()
    {
        cmd.execute();
    }
}

5. Finally a Client class, Its creates an instance of Command implementation and associates with a receiver

public class Client {

    public static void main(String arg[])
    {
        RemoteControl rc = new RemoteControl();
        // Receiver
        Light light = new Light();

        // creates an instance of Command implementation
        Command lightOn = new LightOnCommand(light);
        Command lightOff = new LightOffCommand(light);     

        // For Switch on
        rc.setCommand(lightOn);
        rc.pressButton();

        // For Switch off
        rc.setCommand(lightOff);
        rc.pressButton();
    }
}




No comments:

Post a Comment