当前位置:网站首页>Command mode - attack, secret weapon

Command mode - attack, secret weapon

2022-06-11 11:12:00 zhanyd

scene

As the saying goes, the general trend of the world will converge after a long time , A long time must be divided. , After a great empire in the Central Plains lasted for hundreds of years , It finally fell apart , All the princes set out to fight , feudal lords vying for the throne .

Xiaoshuai stands on his own as king , Lead a hundred thousand troops , March north , fight for territory in ancient central China , Dream of achieving a hegemony .

The small marshal and the great army have conquered several cities in succession , Want to work hard , Take down the famous city as solid as gold , Panyancheng .

lo , The army has been unable to attack for a long time , Heavy losses , Seeing that the besieged city has more than three months , Still no progress , There is a shortage of food and grass here , Xiaoshuai is burning with anxiety .

The Young Marshal asked the military division what to do , The military adviser said :“ I know there will be a fierce battle this time , I was preparing a secret weapon a few months ago , In a few days , At that time, the city will be destroyed , Lord, don't panic .”

Sure enough , In a few days , The military division asked the Young Marshal to come to the front :“ Secret weapons have arrived in the army , Please have a look .”

This is a stone throwing machine developed by the Ministry of work , It can throw stones weighing hundreds of kilograms at a time , It can break the walls of the opponent .
 Insert picture description here
This is a heavy-duty punching car developed by the Ministry of industry , The soldiers hid inside , Can avoid falling rocks from bows and arrows , You can break the enemy's gate .
 Insert picture description here
Finally, this is a magician specially invited from the western regions , Powerful , Then we'll know .
 Insert picture description here
Everything is ready , Just wait for the Lord to give an order , You can take the city .

Xiaoshuai asked :“ The military master knows how to operate these weapons ?”

The military adviser replied :“ The Lord doesn't have to know the details , Just order the attack command , Own skilled soldiers to operate .”

Xiao Shuai was overjoyed , Quickly summon the generals , Make a war plan .

Code implementation

/** *  The command interface  * @author zhanyd * @date 2020-12-26 */
public interface Command {
    
    public void execute();
}
/** *  Specific attack orders  * @author zhanyd * @date 2020-12-26 */
public class FireCommand {
    
    Command command;

    public void setCommand(Command command) {
    
        this.command = command;
    }

    public void fire() {
    
        command.execute();
    }
}
/** *  Catapults  */
public class Catapult {
    

    /** *  Loading stones  */
    public void loadStone() {
    
        System.out.println(" A catapult carries stones ...");
    }

    /** *  Aim at the target  */
    public void aim() {
    
        System.out.println(" The catapult aimed at the target ...");
    }

    /** *  launch  */
    public void fire() {
    
        System.out.println(" Catapult launch !");
    }
}
/** *  Catapult attacks  * @author zhanyd * @date 2020-12-26 */
public class CatapultFireCommand implements Command{
    
    private Catapult catapult;

    public CatapultFireCommand(Catapult catapult) {
    
        this.catapult = catapult;
    }

	/** *  A catapult attack  */
    @Override
    public void execute() {
    
        catapult.loadStone();
        catapult.aim();
        catapult.fire();
    }
}
/** *  Washing vehicles  */
public class RushCar {
    

    /** *  Move  */
    public void move() {
    
        System.out.println(" Rush to the target ...");
    }

    /** *  To hit  */
    public void hit() {
    
        System.out.println(" A collision with a car !");
    }
}
/** *  Vehicle impact attack  * @author zhanyd * @date 2020-12-26 */
public class RushCarFireCommand implements Command {
    
    private RushCar rushCar;

    public RushCarFireCommand(RushCar rushCar) {
    
        this.rushCar = rushCar;
    }

    /** *  A car attack  */
    @Override
    public void execute() {
    
        rushCar.move();
        rushCar.hit();
    }
}
/** *  Magicians  */
public class Magician {
    

    /** *  Sing  */
    public void chant() {
    
        System.out.println(" The magician sings a spell ...");
    }

    /** *  Summon meteorites  */
    public void summonMeteor() {
    
        System.out.println(" The magician summoned the meteorite !");
    }
}
/** *  Mage attacks  * @author zhanyd * @date 2020-12-26 */
public class MagicianFireCommand implements Command{
    
    private Magician magician;

    public MagicianFireCommand(Magician magician) {
    
        this.magician = magician;
    }

    /** *  The magician attacks  */
    @Override
    public void execute() {
    
        magician.chant();
        magician.summonMeteor();
    }
}
/** *  Attack test class  * @author zhanyd * @date 2020-12-26 */
public class FireTest {
    
    public static void main(String[] args) {
    
        FireCommand fireCommand = new FireCommand();
        //  A catapult attack 
        Catapult catapult = new Catapult();
        CatapultFireCommand catapultFireCommand = new CatapultFireCommand(catapult);
        fireCommand.setCommand(catapultFireCommand);
        fireCommand.fire();
        //  A car attack 
        RushCar rushCar = new RushCar();
        RushCarFireCommand rushCarFireCommand = new RushCarFireCommand(rushCar);
        fireCommand.setCommand(rushCarFireCommand);
        fireCommand.fire();
        //  The magician attacks 
        Magician magician = new Magician();
        MagicianFireCommand magicianFireCommand = new MagicianFireCommand(magician);
        fireCommand.setCommand(magicianFireCommand);
        fireCommand.fire();
    }
}
 A catapult carries stones ...
 The catapult aimed at the target ...
 Catapult launch !
 Rush to the target ...
 A collision with a car !
 The magician sings a spell ...
 The magician summoned the meteorite !

Command mode definition

Command mode (Command Pattern): Encapsulate a request as an object , This allows us to parameterize customers with different requests ; Queue or log requests , And support for undo operations . Command mode is an object behavior mode , Its alias is action (Action) Patterns or transactions (Transaction) Pattern .

 Insert picture description here
picture source

The correspondence between the class diagram of the command pattern and the classes in the above code is as follows :

Invoker: It's corresponding to FireCommand class .
Command: It's corresponding to Command class .
ConcreteCommand: It's corresponding to CatapultFireCommand,RushCarFireCommand,MagicianFireCommand class .
Receiver: It's corresponding to Catapult,RushCar,Magician class .
Client: It's corresponding to FireTest class .

The batch

With a loud noise , The other side's walls were covered with gunpowder , Xiaoshuai was amazed , I thought as long as I gave an order , No matter what weapon , Just attack in your own way , Don't worry about me , That's great .

“ newspaper ~~ Lord , Cracks appeared in the enemy's walls , But the gap has not been opened yet !”, The scout from the front reported .

Xiao Shuai got up , Immediately came to the military division and ordered :“ Make the magician , The catapult and the hurling car attack at the same time !”

“ Deling !” The military division immediately conveyed the Lord's order .

/** *  Batch attack command class  * @author zhanyd * @date 2020-12-26 */
public class BatchFireCommand {
    
    List<Command> commandList = new ArrayList<Command>();

    public void addCommand(Command command) {
    
        this.commandList.add(command);
    }

    public void fire() {
    
        commandList.stream().forEach(f -> f.execute());
    }
}
/** *  Batch attack test class  * @author zhanyd * @date 2020-12-26 */
public class BathFireTest {
    
    public static void main(String[] args) {
    
        BatchFireCommand batchFireCommand = new BatchFireCommand();
        //  The magician attacks 
        Magician magician = new Magician();
        MagicianFireCommand magicianFireCommand = new MagicianFireCommand(magician);
        batchFireCommand.addCommand(magicianFireCommand);
        //  A catapult attack 
        Catapult catapult = new Catapult();
        CatapultFireCommand catapultFireCommand = new CatapultFireCommand(catapult);
        batchFireCommand.addCommand(catapultFireCommand);
        //  A car attack 
        RushCar rushCar = new RushCar();
        RushCarFireCommand rushCarFireCommand = new RushCarFireCommand(rushCar);
        batchFireCommand.addCommand(rushCarFireCommand);
        //  Together 
        batchFireCommand.fire();
    }
}
 The magician sings a spell ...
 The magician summoned the meteorite !
 A catapult carries stones ...
 The catapult aimed at the target ...
 Catapult launch !
 Rush to the target ...
 A collision with a car !

A section of the enemy's wall was under the attack , Fall with a bang , A big hole is leaking out , The army was filled with cheers , With a wave of his big hand , Troops from all walks of life swarmed forward ...

summary

Command mode is the decoupling of operations , There is no direct reference relationship between the sender and receiver of the operation , The object sending the request only needs to know how to send the request , Without knowing who the recipient is , And how the recipient completes the request . This is the essence of command mode .

Just like Xiaoshuai just gives orders “ attack ” The order of , It doesn't matter if it's a stone thrower , Or is the magician attacking , How to attack , That's what my men worry about , My Lord, don't care .

Do you think command mode and strategy mode ( Strategic mode plays with infantry , Knights and archers ) It's like ?

In fact, there are still some differences between them , In the strategic model , Different strategies have the same purpose 、 Different implementations 、 They can replace each other . such as ,FightWithSword 、FightWithSpear They are all attacks , One is to attack with a sword , The other is to attack with a long gun , They are equivalent to different algorithms , It's interchangeable .

In command mode , Different commands have different purposes , Corresponding to different processing logic , They can be very different , And they cannot be replaced by each other .

The two have different concerns :

The policy pattern provides a variety of behaviors for the caller to choose , The free choice of algorithm is its focus .

Command mode focuses on decoupling , Encapsulate the content of the request as a command to be executed by the recipient .

Their usage scenarios are different :

The policy pattern is applicable to scenarios where there are multiple behaviors that can be replaced with each other .

Command mode is applicable to the scenario of decoupling two objects with close coupling relationship or revoking multiple command objects .

Code link









 Insert picture description here

原网站

版权声明
本文为[zhanyd]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111054046257.html