设计模式——命令模式(指令模式)

也是在看到阿里巴巴的面试题的时候总结的

作者:haibiscuit

时间:2019:3:13

您的star是我不断前行的动力

https://github.com/haibiscuit

转载请说明出处

七:命令模式(指令模式)
定义:
将一个请求封装成一个对象,从而让你可以用不同的请求对客户进行参数化,对请求排队或者记录请求日志,以及支持可撤销操作
应用实例:
可以参考Hystrix的实现方式,就是采用命令模式实现
使用场景:
可以将接受者的操作封装在命令类中,将命令类封装在调用者中,直接使用调用者,即可完成对操作者的操作,
可以解决解耦和的作用
public class CommandMode {
public static void main(String []args){
Command command; //命令对象
command = new ExitCommand();

FunctionButton functionButton = new FunctionButton(command);
functionButton.click(); //即在调用者调用时,命令对象操作接受者
}
}
/**
* 调用者
*/
class FunctionButton{
private Command command;
public FunctionButton(Command command){ //构造注入
this.command = command;
}
public Command getCommand() {
return command;
}
public void setCommand(Command command) {
this.command = command;
}
public void click(){ //调用命令类的方法
command.Execute();
}
}
/**
* 抽象命令类
*/
abstract class Command{
abstract void Execute();
}
class ExitCommand extends Command{
private SystemExitClass seObj;
public ExitCommand(){
this.seObj = new SystemExitClass();
}
@Override
void Execute() {
seObj.Exit();
}

}

/**
* 接收者
*/
class SystemExitClass{ //退出系统模拟实现类
public void Exit(){
System.out.println("退出系统!");
}
}
总结:
命令模式是一种行为型模式,首先要了解行为的执行模型:
调用者->命令类->接受者
也就是,调用者间接地通过命令类来操作接受者,
这里可以通过拓展命令类的方式来完成对接受者的操作(例如上面的实例中,可以通过点击按钮(调用者)实现其他对接受者的功能,例如退出系统(已实现),打开文档,可以将打开文档的行为封装在接受者中,通过拓展命令类的方式(这里可以实现一个OpenDocuCommand的命令类)来完成对接收者的操作。)

原文地址:https://www.cnblogs.com/haibiscuit/p/10636612.html