Command Pattern

Imaging this:
Client —> Invoker —> Service

In normal conditions when we want to call a method in Service we need to do this in Invoker:

public class Invoker{
    if (client_request_type_1) {call methods in Service}
    if (client_request_type_2) {call methods in Service}
    if (client_request_type_3) {call methods in Service}
}

This strategy obviously has its flaws when these types change or grow. Using the Command pattern, the Invoker and Service are decoupled.

public class Invoker {
    private Command firstCommand;
    private Command secondCommand;
 
    public void doOperation1(){
        firstCommand.execute();
    }
 
    public void doOperation2(){
        secondCommand.execute();
    }
}
 
public class Service{
    public void doThis(){}
    public void doThat(){}
}
 
public interface Command{
    void execute();
}
 
public class FirstConcreteCommand implements Command{
    private Service service;
 
    public void execute(){
        service.doThis();
    }
}
 
public class SecondConcreteCommand implements Command{
    private Service service;
 
    public void execute(){
        service.doThat();
    }
}
 
public class Client{
   public static void main(String[] args){
       Service service = new Service();
       Command cmd1 = new FirstConcreteCommand(can pass Service);
       Command cmd2 = new SecondConcreteCommand(can pass Service);
 
       Invoker i = new Invoker(pass commands in);
 
       i.doOperation1();
       i.doOperation2();
   }
}
command.jpeg

I omitted the dependencies of client with command, concrete commands and service.

page_revision: 13, last_edited: 1218970709|%e %b %Y, %H:%M %Z (%O ago)
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License