命令模式
一. 命令模式
1.1 定义
- 对于“行为请求者”和“行为实现者”,将一组行为抽象为对象,实现二者的松耦合.
1.2 角色
- Command:抽象命令接口.
- ConcreteCommand:具体命令.
- Receiver:最终执行命令的对象.
- Invoker:命令对象的入口.
二. 具体实现
1.1 创建Command接口
public interface ICommand {
void execute();
}
1.2 创建命令执行对象
public class Receiver {
public void execute(){
System.out.println("receiver execute ... ");
}
}
1.3 创建具体Command实现类
public class ConcreteCommandA implements ICommand {
private Receiver receiver;
public ConcreteCommandA(Receiver receiver){
this.receiver = receiver;
}
@Override
public void execute() {
System.out.println("ConcreteCommandA execute ...");
receiver.execute();
}
}
public class ConcreteCommandB implements ICommand {
private Receiver receiver;
public ConcreteCommandB(Receiver receiver){
this.receiver = receiver;
}
@Override
public void execute() {
System.out.println("ConcreteCommandB execute ...");
receiver.execute();
}
}
1.4 创建命令入口
public class Invoker {
private ICommand concreteCommandA, concreteCommandB;
public Invoker(ICommand concreteCommandA, ICommand concreteCommandB){
this.concreteCommandA = concreteCommandA;
this.concreteCommandB = concreteCommandB;
}
public void orderA(){
concreteCommandA.execute();
}
public void orderB(){
concreteCommandB.execute();
}
}
1.5 调用
public static void main(String[] args) {
Receiver receiver = new Receiver();
Invoker invoker = new Invoker(new ConcreteCommandA(receiver), new ConcreteCommandB(receiver));
invoker.orderA();
invoker.orderB();
}
1.6 输出
ConcreteCommandA execute ...
receiver execute ...
ConcreteCommandB execute ...
receiver execute ...
三. 优缺点
3.1 优点
- 降低耦合度.
- 新增一个命令/一组命令简单.
- 调用同一方法实现不同功能.
3.2 缺点
- 会产生过多具体命令类.
四. 源码
https://github.com/Seasons20/DisignPattern.git
END