Статьи

По вашей команде

Шаблон проектирования команд является одним из широко известных шаблонов проектирования, и он подпадает под модель «Поведенческий дизайн» (часть « Банды четырех» ). Как следует из названия, это связано с действиями и событиями в приложении.
Постановка проблемы:
представьте себе сценарий, в котором у нас есть веб-страница, в которой будет несколько меню. Один из способов написания этого кода состоит в том, чтобы иметь несколько условий if-else и выполнять действия при каждом щелчке меню.

private void getAction(String action){
      if(action.equalsIgnoreCase("New")){
          //Create new file
      }
      else if(action.equalsIgnoreCase("Open")){
          //Open existing file
      }
      if(action.equalsIgnoreCase("Print")){
          //Print the file
      }
      if(action.equalsIgnoreCase("Exit")){
          //get out of the application
      }
  }

Мы должны выполнить действия, основанные на строке действия. Однако приведенный выше код имеет слишком много условий if и не может быть прочитан, если он распространяется дальше.

Намерение:

  • Запросчик действия должен быть отделен от объекта, который выполняет это действие.
  • Разрешить инкапсуляцию запроса как объекта. Обратите внимание на эту строку, так как это очень важная концепция для Command Pattern.
  • Разрешить хранение запросов в очереди, т.е. позволяет хранить список действий, которые вы можете выполнить позже.

Solution:
To resolve the above problem the Command pattern is here to rescue. As mentioned above the command pattern moves the above action to objects through encapsulation. These objects when executed it executes the command. Here every command is an object. So we will have to create individual classes for each of the menu actions like NewClass, OpenClass, PrintClass, ExitClass. And all these classes inherit from the Parent interface which is the Command interface. This interface (Command interface) abstracts/wraps all the child action classes.
Now we introduce an Invoker class whose main job is to map the action with the classes which have that action. It basically holds the action and get the command to execute a request by calling the execute() method.
Oops!! We missed another stakeholder here. It is the Receiver class. The receiver class has the knowledge of what to do to carry out an operation. The receiver has the knowledge of what to do when the action is performed.

Structure:

Following are the participants of the Command Design pattern:

  • Command – This is an interface for executing an operation.
  • ConcreteCommand – This class extends the Command interface and implements the execute method. This class creates a binding between the action and the receiver.
  • Client – This class creates the ConcreteCommand class and associates it with the receiver.
  • Invoker – This class asks the command to carry out the request.
  • Receiver – This class knows to perform the operation.

Example:

Steps:

  1. Define a Command interface with a method signature like execute(). In the above example ActionListenerCommand is the command interface having a single execute() method.
  2. Create one or more derived classes that encapsulate some subset of the following: a “receiver” object, the method to invoke, the arguments to pass. In the above example ActionOpen and ActionSave are the Concrete command classes which creates a binding between the receiver and the action. ActionOpen class calls the receiver(in this case the Document class) class’s action method inside the execute(). Thus ordering the receiver class what needs to be done.
  3. Instantiate a Command object for each deferred execution request.
  4. Pass the Command object from the creator  to the invoker.
  5. The invoker decides when to execute().
  6. The client instantiates the Receiver object(Document) and the Command objects and allows the invoker to call the command.

Code Example:

Command interface:

public interface ActionListenerCommand {
    public void execute();
}

Receiver class:

public class Document {
   public void Open(){
       System.out.println("Document Opened");
   }
   public void Save(){
       System.out.println("Document Saved");
   }
}

Concrete Command:

public class ActionOpen implements ActionListenerCommand {
    private Document adoc;
 
    public ActionOpen(Document doc) {
        this.adoc = doc;
    }
    @Override
    public void execute() {
        adoc.Open();
    }
}

Invoker class:

public class MenuOptions {
    private ActionListenerCommand openCommand;
    private ActionListenerCommand saveCommand;
 
    public MenuOptions(ActionListenerCommand open, ActionListenerCommand save) {
        this.openCommand = open;
        this.saveCommand = save;
    }
public void clickOpen(){
    openCommand.execute();
}
public void clickSave(){
    saveCommand.execute();
}
}

Client class:

public class Client {
    public static void main(String[] args) {
        Document doc = new Document();
        ActionListenerCommand clickOpen = new ActionOpen(doc);
        ActionListenerCommand clickSave = new ActionSave(doc);
        MenuOptions menu = new MenuOptions(clickOpen, clickSave);
        menu.clickOpen();
        menu.clickSave();
    }
 
}

Benefits:
Command pattern helps to decouple the invoker and the receiver. Receiver is the one which knows how to perform an action.
A command should be able to implement undo and redo operations.
This pattern helps in terms of extensibility as we can add new command without changing existing code.

Drawback:
The main disadvantage of the Command pattern is the increase in the number of classes for each individual command. These items could have been also done through method implementation. However the command pattern classes are more readable than creating multiple methods using if else condition.

Interesting points:

  • Implementations of java.lang.Runnable and javax.swing.Action follows command design pattern.
  • Command can use Memento to maintain the state required for an undo operation.

 Download Sample Code: