当前位置:网站首页>Command mode - attack, secret weapon
Command mode - attack, secret weapon
2022-06-11 11:12:00 【zhanyd】
List of articles
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 .
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 .
Finally, this is a magician specially invited from the western regions , Powerful , Then we'll know .
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 .
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 .

边栏推荐
- 17.4创建多个线程、数据共享问题分析与案例代码
- 沒有財富就不能自由嗎?
- The first day of the new year | at 8:00 p.m. tomorrow, pulsar Chinese developer and user group meeting registration
- C language course design
- Lifeifei: I am more like a scientist in physics than an engineer
- 迭代器模式--沙场秋点兵
- nft数字藏品系统开发搭建流程
- 2022年安全月各类活动方案汇报(28页)
- Jerry's ble spp open pin_ Code function [chapter]
- 使用Yolov5训练好模型调用电脑自带摄像头时出现问题:TypeError: argument of type “int‘ is not iterable的解决方法
猜你喜欢

迭代器模式--沙场秋点兵

985高校博士因文言文致谢走红!导师评价其不仅SCI写得好...

收货地址列表展示【项目 商城】

IIHS tsp+ annual safety list released: 7 EVs were selected, and there are common problems in pedestrian AEB

MyCat-分库分表
![Electron desktop development (development of an alarm clock [End])](/img/2b/dd59ebc8d11bedfc53020d69f1aa69.png)
Electron desktop development (development of an alarm clock [End])

使用Yolov3训练自己制作数据集,快速上手

李飞飞:我更像物理学界的科学家,而不是工程师|深度学习崛起十年

使用Yolov5训练自己制作的数据集,快速上手

CAP理论听起来很高大上,其实很简单
随机推荐
Rxjs Observable.pipe 传入多个 operators 的执行逻辑分析
沒有財富就不能自由嗎?
Want to be iron man? It is said that many big men use it to get started
不做伪工作者
Inventory of the 9 most famous work task management software at home and abroad
Définir l'adresse de réception par défaut [Centre commercial du projet]
[K-means] K-means learning examples
施一公:我直到博士毕业,对研究也没兴趣!对未来很迷茫,也不知道将来要干什么......
Using domestic MCU (national technology n32g031f8s7) to realize pwm+dma control ws2812
After 95, programmers in big factories were sentenced for deleting databases! Dissatisfied with the leaders because the project was taken over
Source code construction of digital collection system
985高校博士因文言文致谢走红!导师评价其不仅SCI写得好...
Content-Type: multipart/form-data; boundary=${bound}
数字藏品app小程序公众号系统开发
错误的导航分类横条代码版本
Jerry's acquisition of ble distinguishes between reset and wake-up [chapter]
(key points of software engineering review) Chapter IV overall design exercises
Leetcode (Sword finger offer) - 10- ii Frog jumping on steps
RxJs fromEvent 工作原理分析
AcWing 1944. 记录保存(哈希,STL)
