Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Wednesday, February 3, 2016

Using Command Design pattern

Using Command Design pattern


Can any one explain with simple example of Command Pattern. I refer in internet but i got confused.

Answer by Droo for Using Command Design pattern


public interface Command {     public void execute();  }  

For the most part, commands are immutable and contain instructions that encapsulate a single action that is executed on demand. You might also have a RuntimeCommand that accepts instructions upon execution, but this delves more into the Strategy or Decorator Patterns depending on the implementations.

In my own opinion, I think it's very important to heed the immutable context of a command otherwise the command becomes a suggestion. For instance:

public final class StopServerCommand implements Command {      private final Server server;        public StopServerCommand(Server server) { this.server = server; }        public void execute() {          if(server.isRunning()) server.stop();      }  }    public class Application {      //...      public void someMethod() {          stopButton.addActionListener(new ActionListener() {              public void actionPerformed(Event e) {                   stopCommand.execute();              }          });      }  }  

I personally don't really like commands. In my own experience, they only work well for framework callbacks.

If it helps, think of a command in a metaphorical sense; a trained soldier is given a command by his/her commanding officer, and on demand the soldier executes this command.

Answer by java_mouse for Using Command Design pattern


Core J2EE Patterns: Best Practices and Design Strategies.

http://www.amazon.com/Core-J2EE-Patterns-Strategies-ebook/dp/B000OZ0N4E/ref=sr_1_2?ie=UTF8&qid=1319056489&sr=8-2 "Core J2EE Patterns: Best Practices and Design Strategies"

Answer by rsinha for Using Command Design pattern


My requirement is to perform a sequence of tasks (which can be re-used in several Usecases) each with its own exception flow. Found Command pattern's implementation logical here.

I am trying to make it like each action executed by the command (whether normal/alternate flow) can be an exception handler too. However, If the command is registered with another handler then this should be used. Any suggestions for improvement/correction are welcome.

public interface Command {      Result run() throws Exception;      Command onException(ExceptionHandler handler);  }    public class Result {  }    public interface ExceptionHandler {      void handleException(Exception e);  }    public interface Action {      Result execute() throws Exception;  }    public class BasicCommand implements Command {  private Action action;  private ExceptionHandler handler;    public BasicCommand(Action action) {      if (action == null) {          throw new IllegalArgumentException("Action must not be null.");      }      this.action = action;      this.handler = (ExceptionHandler) this.action;  }    @Override  public Command onException(ExceptionHandler handler) {      if (handler != null) {          this.handler = handler;      }      return this;  }    public Result run() throws Exception {      Result result = null;      try {          result = action.execute();      } catch (Exception e) {          handler.handleException(e);      }      return result;  }  

}

public class BasicAction implements Action, ExceptionHandler {      private Object[] params;          public BasicAction(Object... params) {          this.params = params;      }        @Override      public Result execute() throws Exception {          // TODO Auto-generated method stub          return null;      }        @Override      public void handleException(Exception e) {          // TODO exception translation: prepare unchecked application. exception and throw..      }  }    public class Main {        public static void main(String[] args) throws Exception {          int param1 = 10;          String param2 = "hello";            // command will use the action itself as an exception handler          Result result = new BasicCommand(new BasicAction(param1, param2)).run();            ExceptionHandler myHandler = new ExceptionHandler(){              @Override              public void handleException(Exception e) {                  System.out.println("handled by external handler");              }          };          // command with an exception handler passed from outside.            Result result2 = new BasicCommand(new BasicAction(param1, param2)).onException(myHandler).run();        }  }  

Have a look at this article to understand scenarios in which command pattern is useful. Key use case : Asynchronous communication ( Runnable & Thread in java are examples), implement redo actions etc.

Answer by Samuel for Using Command Design pattern


Here is another example you can use to understand how command pattern works, using real life scenarios: You cannot travel from one place to another by airplane without using the command pattern!

If you are a frequent traveler, all you care about as a client is to travel from where you are to another . you don't care about how the pilot will fly the plane or which airline will be available .. you cant really predict that. all you want is to get the the air port and tell them to take you to your destination.

But if you do that, your command to the airport authorities will be laughed at! they need you to supply a command object, which is your ticket. as much as you don't care about which airline or which plane type, when you are ready to fly, you need to supply a ticket command object. The invoker, which is the airport officials needs to check your command (ticket) so that they can validate it, undo it if it is fake, redo it if they made a mistake (without you having to go through the booking process all over).

In short , they want to have complete control of your command (ticket) before deciding whether or not to invoke or execute your command, which lets the airline (the receiver ) execute ( put you on a plane and take you to your destination) .

Mind you, your command (your ticket) already has the information of the receiver (airline) without which the airport officials wont even start to process your ticket in the first place.

The airport authorities could even have a bunch of tickets they are working on. they may choose to delay my ticket and let someone that came after me go through (invoke another persons ticket before mine)

Here is the code :

 [TestClass]      public class Client      {          [TestMethod]          public void MyFlight_UsingCommandPattern()          {              var canadianAirline = new Airline();                AirlineTicket_Command myTicket = new MyAirLineTicket(canadianAirline);                var airportOfficials = new AirportOfficials_Invoker(myTicket);              airportOfficials.ProcessPasengerTicket_And_AllowPassengerToFly_Execute();                //assert not implemented          }      }        public class AirportOfficials_Invoker      {          private AirlineTicket_Command PassengerTicket { set; get; }            public AirportOfficials_Invoker(AirlineTicket_Command passengerTicket)          {              throw new NotImplementedException();          }            public void ProcessPasengerTicket_And_AllowPassengerToFly_Execute()          {              PassengerTicket.Execute();          }      }        public abstract class AirlineTicket_Command      {          protected Airline Airline { set; get; }            protected AirlineTicket_Command(Airline airline)          {              Airline = airline;          }            public abstract void Execute();      }        public class MyAirLineTicket : AirlineTicket_Command      {          public MyAirLineTicket(Airline airline)              : base(airline)          {          }            public override void Execute()          {              Airline.FlyPassenger_Action();          }      }        public class Airline      {          public void FlyPassenger_Action()          {  //this will contain all those stuffs of getting on the plane and flying you to your destination          }      }  

Answer by ravindra for Using Command Design pattern


You can think of Command pattern workflow as follows.

  1. Command declares an interface for all commands, providing a simple execute() method which asks the Receiver of the command to carry out an operation.

  2. The Receiver has the knowledge of what to do to carry out the request.

  3. The Invoker holds a command and can get the Command to execute a request by calling the execute method.

  4. The Client creates ConcreteCommands and sets a Receiver for the command.

  5. The ConcreteCommand defines a binding between the action and the receiver.

  6. When the Invoker calls execute the ConcreteCommand will run one or more actions on the Receiver.

    /* Command class */  public interface Runnable {      public abstract void run();  }    /* Invoker */  public Thread implements Runnable {     private Runnable target;     public synchronized void start(){         // This one starts thread by calling run()   }   public void run() {      if (target != null) {          target.run();      }  }  

    }

    /* ConcreteCommand is the class in your application which implements Runnable  */    /* Client is your application class which creates new Thread(ConcreteCommand) */  

Another simple example:

public class CommandDemo{      public static void main(String args[]){            // On command for TV with same invoker           Receiver r = new TV();          Command onCommand = new OnCommand(r);          Invoker invoker = new Invoker(onCommand);          invoker.execute();            // On command for DVDPlayer with same invoker           r = new DVDPlayer();          onCommand = new OnCommand(r);          invoker = new Invoker(onCommand);          invoker.execute();            // Off Command for TV with same invoker          r = new TV();          Command offCommand = new OffCommand(r);          invoker =  new Invoker(offCommand);          invoker.execute();              // Off Command for TV with same invoker          r = new DVDPlayer();          offCommand = new OffCommand(r);          invoker =  new Invoker(offCommand);          invoker.execute();        }  }  interface Command {      public void execute();  }    class Receiver {      public void switchOn(){          System.out.println("Switch on from:"+this.getClass().getSimpleName());      }      public void switchOff(){          System.out.println("Switch off from:"+this.getClass().getSimpleName());      }  }    class OnCommand implements Command{        private Receiver receiver;        public OnCommand(Receiver receiver){          this.receiver = receiver;      }      public void execute(){          receiver.switchOn();      }  }      class OffCommand implements Command{        private Receiver receiver;      public OffCommand(Receiver receiver){          this.receiver = receiver;      }      public void execute(){          receiver.switchOff();      }  }    class Invoker {      public Command command;        public Invoker(Command c){          this.command=c;      }      public void execute(){          this.command.execute();      }  }    class TV extends Receiver{      public TV(){        }      public String toString(){          return this.getClass().getSimpleName();      }  }  class DVDPlayer extends Receiver{      public DVDPlayer(){        }      public String toString(){          return this.getClass().getSimpleName();      }  }  

output:

Switch on from:TV  Switch on from:DVDPlayer  Switch off from:TV  Switch off from:DVDPlayer  

Have a look at this dzone and journaldev and Wikipedia articles.

Source code as Wikipedia page is simple, cleaner and self explanatory.


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.