Definition of Command Patterns
The command pattern abstracts a set of behaviors into objects and achieves loose coupling between the two. This is the Command Pattern (Command Pattern).
Model:
-
Invoker: The caller is responsible for calling after receiving the command
-
Receiver: The receiver, that is, the person who executes the command, is the hardest
-
Command: Commander, encapsulated command class
The following is a simple example to understand the command mode.
Example description
Since there is an order, take "project manager" - "developer" as an example. For example, there is an outsourced project that needs to be developed. After the development is completed, Party A requests to change a certain function. The following code is used to explain in detail:
1. First define an abstract Receiver, because there is more than one developer
public abstract class AbstractReceiver {
//Write item
public abstract void write () ;
//Add, delete and modify items
public abstract void change () ;
//Submit program
public abstract void ubmit () ;
}
2. Define a specific Receiver, here it is assumed that there are two developers
public class ReceiverA extends AbstractReceiver{
@Override
public void write() {
Log.d("qzs","写代码");
}
@Override
public void change() {
Log.d("qzs","改需求");
}
@Override
public void submit() {
Log.d("qzs","提交");
}
}
public class ReceiverB extends AbstractReceiver {
@Override
public void write() {
Log.d("qzs","写代码");
}
@Override
public void change() {
Log.d("qzs","改需求");
}
@Override
public void submit() {
Log.d("qzs","提交");
}
}
3.定义Command,命令类,也就是刚才说的甲方要求改一改某个功能的命令,假如此功能是开发人员A改:
public abstract class AbstractCommand {
ReceiverA receiverA=new ReceiverA(); //开发人员A
ReceiverB receiverB=new ReceiverB(); //开发人员B
//执行
public abstract void excute();
}
public class ChangeFunctionCommand extends AbstractCommand {
@Override
public void excute() {
receiverA.change();
receiverA.submit();
}
}
4.定义Invoker类,也就是项目经理,负责安排调用
public class Invoker {
private AbstractCommand command;
//设置命令
public void setCommand(AbstractCommand command) {
this.command = command;
}
// 执行命令
public void Action(){
command.excute();
}
5.调用
//定义一个项目经理-张三
Invoker ZHANGSAN=new Invoker();
//定义修改功能的命令并执行
AbstractCommand command=new ChangeFunctionCommand();
ZHANGSAN.setCommand(command);
ZHANGSAN.Action();
运行后:
命令模式的优缺点及其他
1.优点:
-
降低对象之间的耦合度
-
新的命令可以很容易地加入到系统中
-
可以比较容易地设计一个组合命令
-
调用同一方法实现不同的功能
2.缺点:
使用命令模式可能会导致某些系统有过多的具体命令类。因为针对每一个命令都需要设计一个具体命令类,因此某些系统可能需要大量具体命令类,这将影响命令模式的使用。
3.使用场景:
-
需要对行为进行记录,撤销,重做,事务处理时
-
需要抽象出待执行的动作,然后以参数的形式提供出来
4.附加:
如果有人问了,撤销的操作怎么做,其实很简单。在抽象的接收类中定义一个“撤销”的方法。然后再定义一个撤销Command来增加这个撤销命令就好了。
本文学习参考了《设计模式之禅》以及网上信息...