命令模式:将请求封装成对象,以便是用不同的请求参数化其他对象,同时也支持撤销操作。
命令把命令的动作和命令的接受者封装在一起,也就是发出请求的对象和接受与执行这些请求的对象分隔开来。
为什么命令的发出者不直接调用执行者呢?反而在中间包装了一层命令呢?这样的封装是为了实现调用者和接受者之间的解耦,同时还可以设计出多种命令形式(业务)。
#pragma once
//命令基类
class WCommand {
public:
WCommand();
~WCommand();
virtual void execute();
virtual void undo();
};
#include "WCommand.h"
WCommand::WCommand() {
}
WCommand::~WCommand() {
}
void WCommand::execute() {
}
void WCommand::undo() {
}
#pragma once
#include "WCommand.h"
//复制命令
class ShareBuffer;
class CopyCommand : public WCommand {
public:
CopyCommand(ShareBuffer* buffer);
~CopyCommand();
virtual void execute()override;
virtual void undo()override;
private:
ShareBuffer* _buffer = nullptr;
};
#include "CopyCommand.h"
#include "ShareBuffer.h"
CopyCommand::CopyCommand(ShareBuffer* buffer) {
_buffer = buffer;
}
CopyCommand::~CopyCommand() {
}
void CopyCommand::execute() {
_buffer->copy();
}
void CopyCommand::undo() {
_buffer->undoCopy();
}
#pragma once
#include "WCommand.h"
//删除命令
class ShareBuffer;
class DeleteCommand :public WCommand {
public:
DeleteCommand(ShareBuffer* buffer);
~DeleteCommand();
virtual void execute()override;
virtual void undo()override;
private:
ShareBuffer* _buffer = nullptr;
};
#include "DeleteCommand.h"
#include "ShareBuffer.h"
DeleteCommand::DeleteCommand(ShareBuffer* buffer) {
_buffer = buffer;
}
DeleteCommand::~DeleteCommand() {
}
void DeleteCommand::execute() {
_buffer->deleteBuffer();
}
void DeleteCommand::undo() {
_buffer->undoDelete();
}
#pragma once
//共享内存
class ShareBuffer {
public:
ShareBuffer();
~ShareBuffer();
void copy();
void undoCopy();
void deleteBuffer();
void undoDelete();
};
#include "ShareBuffer.h"
#include <stdio.h>
ShareBuffer::ShareBuffer() {
}
ShareBuffer::~ShareBuffer() {
}
void ShareBuffer::copy() {
printf("复制内存内容\n");
}
void ShareBuffer::undoCopy() {
printf("取消复制内存内容\n");
}
void ShareBuffer::deleteBuffer() {
printf("删除内存内容\n");
}
void ShareBuffer::undoDelete() {
printf("恢复内存内容\n");
}
调用:
#include <stdio.h>
#include "ShareBuffer.h"
#include "WCommand.h"
#include "CopyCommand.h"
#include "DeleteCommand.h"
int main() {
ShareBuffer* buffer = new ShareBuffer;
WCommand* command = new CopyCommand(buffer);
command->execute();
command->undo();
command = new DeleteCommand(buffer);
command->execute();
command->undo();
return 0;
}
运行结果:
aaa