JavaRush /Java Blog /Random EN /Command pattern in your own words
Roman_kh
Level 33
Харьков

Command pattern in your own words

Published in the Random EN group

Hello everyone, Forum members!

I have thoroughly (it seems to me) figured out the pattern Commandand I want to try to talk about it “in my own words.” Command pattern in your own words - 1Based on Wikipedia, we can find out that its purpose is to create a structure in which the sending class and the receiving class do not directly depend on each other. Organizing a callback to a class that includes the sender class . In principle, it is written clearly and correctly, but this is in theory. How to do this? This is where the problems begin, because... the description is no longer so clear and obvious. Therefore, I figured it out, I decided to tell you how I understood it, maybe it will be useful to someone: Based on the description of the purpose of this pattern, I will combine the description with the code to make it more clear, because in the same Wikipedia they generalized it for many languages ​​and therefore the description is separated from the example. There are four terms in this pattern, let's take them for granted for now: commands( command), command receiver( receiver), command caller( invoker) and client( client). I will take an example from the same Wikipedia, it is quite tolerable. The task is a class Lightthat can do two things: turn the light on and turn it off. In terms of the pattern it will be “command receiver ( receiver)”
/*Receiver class*/

public class Light{
     public Light(){  }

     public void turnOn(){
        System.out.println("The light is on");
     }

     public void turnOff(){
        System.out.println("The light is off");
     }
}
Let's create an interface with one method execute()that will execute and which is called in terms of the "command ( command)" pattern
/*the Command interface*/

public interface Command{
    void execute();
}
It is necessary to encapsulate the execution of class skills Light. To do this, we will create classes TurnOnLightCommandand TurnOffLightCommandthat implement the interface Commandand which will accept a class object in the constructor Light. And each of them will perform only one action. One will call the method turnOn(), and the other will call turnOff().
/*the Command for turning on the light*/

public class TurnOnLightCommand implements Command{
   private Light theLight;

   public TurnOnLightCommand(Light light){
        this.theLight=light;
       }

   public void execute(){
      theLight.turnOn();
   }
}

/*the Command for turning off the light*/

public class TurnOffLightCommand implements Command{
   private Light theLight;

   public TurnOffLightCommand(Light light){
        this.theLight=light;
       }

   public void execute(){
      theLight.turnOff();
   }
}
Now it's time to create an object that accepts these encapsulated object methods Light. In terms of the pattern, it is called the command caller (invoker). Let's call it Switchand let it accept variables in the constructor Commandthat will be used in the created methods flipUp()and flipDown().
/*the Invoker class*/

public class Switch {
    private Command flipUpCommand;
    private Command flipDownCommand;

    public Switch(Command flipUpCommand,Command flipDownCommand){
         this.flipUpCommand=flipUpCommand;
         this.flipDownCommand=flipDownCommand;
    }

    public void flipUp(){
         flipUpCommand.execute();
    }

    public void flipDown(){
         flipDownCommand.execute();
    }
}
And of course, we’ll create a class that will use them to understand what’s going on in general. It will be called the main method, in which all the action will take place:
/*The test class*/
public class TestCommand{
   public static void main(String[] args){
       // создаем an object, который будет использоваться
       Light l=new Light();
       // создаем an objectы для всех умений an object Light:
       Command switchUp=new TurnOnLightCommand(l);
       Command switchDown=new TurnOffLightCommand(l);

       // Создаемтся invoker, с которым мы будем непосредственно контактировать:
       Switch s=new Switch(switchUp,switchDown);

       // вот проверка этого, используем методы:
       s.flipUp();
       s.flipDown();
   }
}
The output will be the following:
"The light is on"
"The light is off"

Where is this applied?

The purpose is clear what and why this is needed, namely: in a situation where you need to separate a specific execution, this is very convenient. So that the use of some functions does not depend on a specific implementation and it can be changed without damaging the system. something like this...) Write your comments, let's discuss, maybe something can be made simpler and told better, we will edit everything if necessary) So that for those who will read for the first time, it is as clear as possible. Well, whoever likes the article puts a “+” on it :) This is important for me) Over time, I want to write more about Builder, Singletonand others. See also my other articles:
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION