C++设计模式-命令模式
生活随笔
收集整理的這篇文章主要介紹了
C++设计模式-命令模式
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
目錄
?
?
基本概念
代碼與實(shí)例
?
基本概念
命令模式(Command),將一個(gè)請(qǐng)求封裝為對(duì)象,從而使你看用不同的請(qǐng)求對(duì)客戶端進(jìn)行參數(shù)化;對(duì)請(qǐng)求排隊(duì)或記錄請(qǐng)求日志,以及支持可撤銷操作。
命令模式的作用:
? ? ? ? ? 1. 能比較容易的設(shè)計(jì)一個(gè)命令隊(duì)列;
? ? ? ? ? 2. 在需要的情況下,可以比較容易地將命令記入日志;
? ? ? ? ? 3. 允許接收請(qǐng)求的一方?jīng)Q定是否要否決請(qǐng)求;
? ? ? ? ? 4. 可以容易的實(shí)現(xiàn)對(duì)請(qǐng)求的撤銷和重做;
? ? ? ? ? 5. 由于加進(jìn)的新的具體命令類不影響其他類,因此增加新的具體命令類很容易。
?
UML圖如下(此圖來源于大話設(shè)計(jì)模式)
?
代碼與實(shí)例
程序運(yùn)行截圖如下:
源碼如下:
Head.h
#ifndef HEAD_H #define HEAD_H#include <iostream> #include <string> using namespace std;//Receiver類,知道如何實(shí)施與執(zhí)行一個(gè)與請(qǐng)求相關(guān)的操作,任何類都可能作文一個(gè)接收者 class Receiver{public:void action();~Receiver(); };//Command類,用來聲明執(zhí)行操作的接口 class Command{public:virtual void execute();Command(Receiver *receiver);virtual ~Command();protected:Command();Command(Command &c);Command &operator = (Command &c);Receiver *m_receiver; };//ConcreteCommand類,將一個(gè)接收者對(duì)象綁定于一個(gè)動(dòng)作,調(diào)用接收這相應(yīng)的操作,以實(shí)現(xiàn)Execute class ConcreteCommand: public Command{public:ConcreteCommand(Receiver *receiver);void execute();~ConcreteCommand(); };//Invoker類,要求該命令執(zhí)行這個(gè)請(qǐng)求 class Invoker{public:void setCommand(Command *command);void executeCommand();private:Command *m_command; };#endifHead.cpp
#include "Head.h"void Command::execute() {}Command::~Command() {cout << "Command::~Command()" << endl; }Command::Command() {}Command::Command(Command &c) {}Command::Command(Receiver *receiver) {m_receiver = receiver; }Command & Command::operator=(Command &c) {return Command(); }void Receiver::action() {cout << "執(zhí)行請(qǐng)求!" << endl; }Receiver::~Receiver() {cout << "Receiver::~Receiver()" << endl; }ConcreteCommand::ConcreteCommand(Receiver *receiver) : Command(receiver) {}void ConcreteCommand::execute() {m_receiver->action(); }ConcreteCommand::~ConcreteCommand() {cout << "ConcreteCommand::~ConcreteCommand()" << endl; }void Invoker::setCommand(Command *command) {m_command = command; }void Invoker::executeCommand() {m_command->execute(); }main.cpp
#include "Head.h"int main(int *argc, int *argv){Receiver *r = new Receiver;Command *c = new ConcreteCommand(r);Invoker *i = new Invoker;i->setCommand(c);i->executeCommand();delete r;delete c;delete i;getchar();return 0; }?
總結(jié)
以上是生活随笔為你收集整理的C++设计模式-命令模式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: QML笔记-TextEdit的使用
- 下一篇: Spring Boot笔记-拦截器相关(