行为型模型 命令模式
Command
Command命令的抽象类。
ConcreteCommand
Command的具体实现类。
Receiver
需要被调用的目标对象。
Invorker
通过Invorker执行Command对象。
适用于:
是将一个请求封装为一个对象,从而使你可用不同的请求对客户端进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。
/** * 行为型模型 命令模式 * Command模式也叫命令模式 ,是行为设计模式的一种。 * Command模式通过被称为 Command的类封装了对目标对象的调用行为以及调用参数。 * * */ #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <string> #include <list> class Vendor { public: void saleBanana() { std::cout << "卖香蕉" << std::endl; } void saleApple() { std::cout << "卖苹果" << std::endl; } }; class Command { public: virtual void sale() = 0; virtual ~Command() {} }; class BananaCommand: public Command { public: BananaCommand(Vendor * v) { m_v = v; } Vendor * getV(Vendor * v) { return m_v; } void setV(Vendor *v) { m_v = v; } virtual void sale() override { m_v->saleBanana(); } private: Vendor * m_v; }; class AppleCommand: public Command { public: AppleCommand(Vendor * v) { m_v = v; } Vendor * getV(Vendor * v) { return m_v; } void setV(Vendor *v) { m_v = v; } virtual void sale() override { m_v->saleApple(); } private: Vendor * m_v; }; class Waiter { public: Command *getCommand() { return m_command; } void setCommand(Command * c) { m_command = c; } void sale() { m_command->sale(); } private: Command * m_command; }; class AdvWaiter { public: AdvWaiter() { m_list = new std::list<Command *>; m_list->clear(); } ~AdvWaiter() { delete m_list; m_list = nullptr; } void setCommands(Command * c) { m_list->push_back(c); } std::list<Command *> * getCommands() { return m_list; } void sale() { for (std::list<Command *>::iterator it = m_list->begin(); it != m_list->end(); it++) { (*it)->sale(); } } private: std::list<Command *> * m_list; }; void mytest() { std::cout << "小商贩 直接 卖 水果" << std::endl; Vendor * v1 = new Vendor(); v1->saleApple(); v1->saleBanana(); delete v1; v1 = nullptr; std::cout << "小商贩 通过命令 卖 水果" << std::endl; Vendor * v2 = new Vendor(); AppleCommand * ac2 = new AppleCommand(v2); ac2->sale(); BananaCommand * bc2 = new BananaCommand(v2); bc2->sale(); delete bc2; bc2 = nullptr; delete ac2; ac2 = nullptr; delete v2; v2 = nullptr; std::cout << "小商贩 通过waiter 卖 水果" << std::endl; Vendor * v3 = new Vendor(); AppleCommand *ac3 = new AppleCommand(v3); BananaCommand *bc3 = new BananaCommand(v3); Waiter *w3 = new Waiter(); w3->setCommand(ac3); w3->sale(); w3->setCommand(bc3); w3->sale(); delete w3; w3 = nullptr; delete bc3; bc3 = nullptr; delete ac3; ac3 = nullptr; delete v3; v3 = nullptr; std::cout << "小商贩 通过advwaiter 批量下单 卖水果" << std::endl; Vendor * v4 = new Vendor(); AppleCommand * ac4 = new AppleCommand(v4); BananaCommand * bc4 = new BananaCommand(v4); AdvWaiter *w4 = new AdvWaiter(); w4->setCommands(ac4); w4->setCommands(bc4); w4->sale(); delete v4; v4 = nullptr; delete w4; w4 = nullptr; delete bc4; bc4 = nullptr; delete ac4; ac4 = nullptr; delete v4; v4 = nullptr; return; } int main() { mytest(); system("pause"); return 0; }
时间: 2024-11-08 03:37:04