设计模式(16)-命令模式及实现
基本概念
命令模式提供了一种将请求封装成对象的方法,使得请求的发送者与请求的接收者之间不直接耦合。
优点:
命令模式的效果在于解耦命令的发送者和接收者,从而支持更灵活的代码组织。它允许您轻松地添加新的命令,排队命令,记录命令历史,甚至实现撤消和重做功能。
缺点:
命令模式也可能引入一些复杂性,因为您需要为每个操作创建一个具体命令类。
https://gitee.com/want-to-lose-another-30-jin/design-pattern-implementation
设计模式具体实现
角色
1、命令(Command):
定义命令的接口,声明执行操作的方法。
2、具体命令(Concrete Command):
实现命令接口,对应于具体的行为和接收者。
3、接收者(Receiver):
知道如何实施与执行一个请求相关的操作。
4、调用者/请求者(Invoker):
要求该命令被执行,它通常对命令对象进行参数化,然后执行该命令。
java实现
package shejimoshi.minglingmoshi;
// 命令接口
public interface Command {
void execute();
}
package shejimoshi.minglingmoshi;
// 具体命令
public class ConcreteCommand implements Command {
private Receiver receiver;
public ConcreteCommand(Receiver receiver) {
this.receiver = receiver;
}
@Override
public void execute() {
receiver.action();
}
}
package shejimoshi.minglingmoshi;
// 调用者
public class Invoker {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void trigger() {
command.execute();
}
}
package shejimoshi.minglingmoshi;
// 接收者
public class Receiver {
public void action() {
System.out.println("Receiver performs the action.");
}
}
package shejimoshi.minglingmoshi;
public class client {
public static void main(String[] args) {
Receiver receiver = new Receiver();
Command command = new ConcreteCommand(receiver);
Invoker invoker = new Invoker();
invoker.setCommand(command);
invoker.trigger(); // Receiver performs the action.
}
}
c++实现
#include <iostream>
// 接收者
class Receiver {
public:
void action() {
std::cout << "Receiver performs the action." << std::endl;
}
};
// 命令接口
class Command {
public:
virtual ~Command() {}
virtual void execute() = 0;
};
// 具体命令
class ConcreteCommand : public Command {
private:
Receiver* receiver;
public:
ConcreteCommand(Receiver* receiver) : receiver(receiver) {}
void execute() override {
receiver->action();
}
};
// 调用者
class Invoker {
private:
Command* command;
public:
void setCommand(Command* command) {
this->command = command;
}
void trigger() {
command->execute();
}
~Invoker() {
delete command;
}
};
// 客户端
int main() {
Receiver* receiver = new Receiver();
Command* command = new ConcreteCommand(receiver);
Invoker invoker;
invoker.setCommand(command);
invoker.trigger(); // Receiver performs the action.
delete receiver; // 清理接收者
return 0;
}