Thursday, November 17, 2011

Command Behavioral Design Pattern


Command is most commonly used behavioral design pattern. In this, object is used to represent and encapsulate all the information needed to call a method at a later time.

Implementation:

Command.java:
public interface Command {
      public abstract void execute();
}
RecieverOne.java:
public class RecieverOne implements Command {

      @Override
      public void execute() {
            System.out.println("I am Reciever One.");
      }
}
RecieverTwo.java:
public class RecieverTwo implements Command {
      @Override
      public void execute() {
            System.out.println("I am Reciever Two.");
      }
}
Invoker.java:
public class Invoker {
      public void execute(Command cmd){
            cmd.execute();
      }
}
Client.java:
public class Client {
      public static void main(String[] args) {
            Command cmd1 = new RecieverOne();
            Command cmd2 = new RecieverTwo();
            Invoker invoker = new Invoker();
            invoker.execute(cmd1);
            invoker.execute(cmd2);
      }
}

No comments:

Post a Comment