• 【C/C++学院】0901-设计模式的汇总演练


    备忘录模式

    数据库的备份,文档编辑中的撤销等功能

    #include <iostream>
    #include <string>
    #include <vector>
    using namespace std;
    
    //备忘录模式:备忘录对象是一个用来存储另外一个对象内部状态的快照的对象。
    //备忘录模式的用意是在不破坏封装的条件下,将一个对象的状态捉住,
    //并外部化。存储起来。从而能够在将来合适的时候把这个对象还原到存储起来的状态。
    //同一时候跟几个MM聊天时。一定要记清楚刚才跟MM说了些什么话
    //,不然MM发现了会不高兴的哦。幸亏我有个备忘录,
    //刚才与哪个MM说了什么话我都拷贝一份放到备忘录里面保存,
    //这样能够随时察看曾经的记录啦
    //设计须要回放的软件。记录一下事物的状态。

    数据库备份,文档的编译,撤销,恢复 //设计备忘录三大步骤 //1.设计记录的节点,存储记录,//记录鼠标,键盘的状态 //2.设计记录的存储。vector,list,map,set,链表,图,数组。树 //3.操作记录的类。记录节点状态,设置节点状态,显示状态。0.1秒记录一下 //备忘录的节点。 class Memo { public: string state; Memo(string state) //记录当前的状态, { this->state = state; } }; class Originator//类的包括备忘录的节点 { public: string state; void setMemo(Memo *memo) { state = memo->state; } Memo *createMemo() { return new Memo(state); } void show() { cout << state << endl; } }; //备忘录的集合 class Caretaker { public: vector<Memo *> memo; void save(Memo *memo) { (this->memo).push_back(memo); } Memo *getState(int i) { return memo[i]; } }; int main1() { Originator *og = new Originator(); Caretaker *ct = new Caretaker(); og->state = "on"; og->show(); ct->save(og->createMemo()); og->state = "off"; og->show(); ct->save(og->createMemo()); og->state = "middle"; og->show(); ct->save(og->createMemo()); og->setMemo(ct->getState(1)); og->show(); og->setMemo(ct->getState(2)); og->show(); cin.get(); return 0; }

    策略模式

    依赖于多态。

    360服务端更新杀毒脚本进行client杀毒的操作。

    逻辑脚本存储在server,接口在client进行实现。

    #include <iostream>
    #include <cmath>
    #include <string>
    using namespace std;
    
    //策略模式:策略模式针对一组算法,将每个算法封装到具有共同接口的独立的类中,
    //从而使得它们能够相互替换。策略模式使得算法能够在不影响到client的情况下
    //发生变化。策略模把行为和环境分开。环境类负责维持和查询行为类,
    //各种算法在详细的策略类中提供。因为算法和环境独立开来。算法的增减。
    //改动都不会影响到环境和client。

    //跟不同类型的MM约会。要用不同的策略,有的请电影比較好, //有的则去吃小吃效果不错,有的去海边浪漫最合适。单目的都是为了得到MM的芳心, //我的追MM锦囊中有好多Strategy哦。 //策略的抽象类,接口,抽象类的指针能够訪问全部子类对象,(纯虚函数) //实现的各种策略。各种策略的实现类,都必须继承抽象类 //策略的设置接口类,设置不同策略 class CashSuper { public: virtual double acceptMoney(double money) = 0;//抽象类,收钱的纯虚函数 }; class CashNormal :public CashSuper { public: double acceptMoney(double money)//正常收钱 { return money; } }; class CashRebate :public CashSuper //打折 { private: double discount; public: CashRebate(double dis) //折扣 { discount = dis; } double acceptMoney(double money)//收钱 { return money*discount;//折扣 } }; class CashReturn :public CashSuper { private: double moneyCondition; double moneyReturn; public: CashReturn(double mc, double mr)//花多少钱,返回多少钱 { moneyCondition = mc; moneyReturn = mr; } double acceptMoney(double money)//收钱,返款 { double result = money; if (money >= moneyCondition) { result = money - floor(money / moneyCondition)*moneyReturn; } return result; } }; class CashContext { private: CashSuper *cs; public: CashContext(string str)//设置策略 { if (str == "正常收费") { cs = new CashNormal(); } else if (str == "打9折") { cs = new CashRebate(0.9); } else if (str == "满1000送200") { cs = new CashReturn(1000, 200); } } double getResult(double money) { return cs->acceptMoney(money); } }; int main123 () { double money = 1000; CashContext *cc = new CashContext("正常收费"); cout << cc->getResult(money); cin.get(); return 0; }

    抽象工厂

    #include <iostream>
    #include <string>
    using namespace std;
    
    //工厂模式:客户类和工厂类分开。
    //消费者不论什么时候须要某种产品,仅仅需向工厂请求即可。
    
    //消费者无须改动就能够接纳新产品。

    缺点是当产品改动时, //工厂类也要做对应的改动。如:怎样创建及怎样向client提供。

    // //追MM少不了请吃饭了,麦当劳的鸡翅和肯德基的鸡翅都是MM爱吃的东西, //尽管口味有所不同,但无论你带MM去麦当劳或肯德基, //仅仅管向服务员说“来四个鸡翅”即可了。麦当劳和肯德基就是生产鸡翅的Factory。

    //消费者不固定,工厂者不固定,(工厂依据消费者的行为进行动作) //实现消费者抽象基类,消费者派生类的实现,实例化就是消费者 //操作的抽象基类。实现派生类各种操作。实例化的操作 //工厂的抽象类,抽象类包括了两个抽象类的接口(消费者。操作) //抽象类实现了工厂类的抽象,实例化的派生类,实现工厂, //依据用户设置用户,依据操作设置操作 class IUser { public: virtual void getUser() = 0; //纯虚接口类,抽象类 virtual void setUser() = 0; }; class SqlUser :public IUser //继承抽象实现sql数据库使用者的实例化 { public: void getUser() { cout << "在sql中返回user" << endl; } void setUser() { cout << "在sql中设置user" << endl; } }; class AccessUser :public IUser //继承抽象实现access数据库使用者的实例化 { public: void getUser() { cout << "在Access中返回user" << endl; } void setUser() { cout << "在Access中设置user" << endl; } }; class IDepartment //抽象类,提供接口 { public: virtual void getDepartment() = 0; virtual void setDepartment() = 0; }; class SqlDepartment :public IDepartment //SQL操作的实现 { public: void getDepartment() { cout << "在sql中返回Department" << endl; } void setDepartment() { cout << "在sql中设置Department" << endl; } }; class AccessDepartment :public IDepartment //access操作的实现 { public: void getDepartment() { cout << "在Access中返回Department" << endl; } void setDepartment() { cout << "在Access中设置Department" << endl; } }; class IFactory //抽象工厂 { public: virtual IUser *createUser() = 0; virtual IDepartment *createDepartment() = 0; }; class SqlFactory :public IFactory //抽象工厂一个实现 { public: IUser *createUser() { return new SqlUser(); } IDepartment *createDepartment() { return new SqlDepartment(); } }; class AccessFactory :public IFactory // 抽象工厂一个实现 { public: IUser *createUser() { return new AccessUser(); } IDepartment *createDepartment() { return new AccessDepartment(); } }; /*************************************************************/ //变相的实现了静态类 class DataAccess { private: static string db; //string db="access"; public: static IUser *createUser() { if (db == "access") { return new AccessUser(); } else if (db == "sql") { return new SqlUser(); } } static IDepartment *createDepartment() { if (db == "access") { return new AccessDepartment(); } else if (db == "sql") { return new SqlDepartment(); } } }; string DataAccess::db = "sql"; /*************************************************************/ int main() { //IFactory *factory=new SqlFactory(); IFactory *factory;//抽象工厂 IUser *user;//抽象消费者 IDepartment *department;//提供的操作 factory = new AccessFactory();//基类的指针指指向派生类的对象 user = factory->createUser();//基类的指针指向派生类的对象 department = factory->createDepartment();//基类的指针指向派生类的对象 user->getUser(); user->setUser();//訪问acesss接口 department->getDepartment(); department->setDepartment();//接口 user = DataAccess::createUser(); department = DataAccess::createDepartment(); user->getUser(); user->setUser(); department->getDepartment(); department->setDepartment(); cin.get(); return 0; }

    工厂方法模式

    #include <iostream>
    #include <string>
    using namespace std;
    
    //工厂方法模式:核心工厂类不再负责全部产品的创建。
    //而是将详细创建的工作交给子类去做,成为一个抽象工厂角色
    //,仅负责给出详细工厂类必须实现的接口。
    //而不接触哪一个产品类应当被实例化这样的细节。
    
    //请MM去麦当劳吃汉堡,不同的MM有不同的口味。
    //要每一个都记住是一件烦人的事情,我一般採用Factory Method模式。
    //带着MM到服务员那儿,说“要一个汉堡”,详细要什么样的汉堡呢,
    //让MM直接跟服务员说即可了。

    class Operation { public: double numberA, numberB; virtual double getResult()// { return 0; } }; class addOperation :public Operation { double getResult() { return numberA + numberB; } }; class subOperation :public Operation { double getResult() { return numberA - numberB; } }; class mulOperation :public Operation { double getResult() { return numberA*numberB; } }; class divOperation :public Operation { double getResult() { return numberA / numberB; } }; class IFactory { public: virtual Operation *createOperation() = 0; }; class AddFactory :public IFactory { public: static Operation *createOperation() { return new addOperation(); } }; class SubFactory :public IFactory { public: static Operation *createOperation() { return new subOperation(); } }; class MulFactory :public IFactory { public: static Operation *createOperation() { return new mulOperation(); } }; class DivFactory :public IFactory { public: static Operation *createOperation() { return new divOperation(); } }; int mainw() { Operation *oper = MulFactory::createOperation(); oper->numberA = 9; oper->numberB = 99; cout << oper->getResult() << endl; cin.get(); return 0; }

    简单工厂模式

    #include <iostream>
    #include <string>
    using namespace std;
    
    //工厂模式:客户类和工厂类分开。
    //消费者不论什么时候须要某种产品,仅仅需向工厂请求即可。
    //消费者无须改动就能够接纳新产品。缺点是当产品改动时。
    //工厂类也要做对应的改动。

    如:怎样创建及怎样向client提供。 // //追MM少不了请吃饭了。麦当劳的鸡翅和肯德基的鸡翅都是MM爱吃的东西, //尽管口味有所不同,但无论你带MM去麦当劳或肯德基。 //仅仅管向服务员说“来四个鸡翅”即可了。

    麦当劳和肯德基就是生产鸡翅的Factory。

    //第一,基类存放数据 //第二,派生类有非常多,派生类存放数据的操作 //第三实现接口类,用静态函数实现调用各种派生类 class Operation //基类存放数据 { public: double numberA, numberB;//两个数 virtual double getResult()//获取结果 { return 0; } }; class addOperation :public Operation//派生类存放操作 { double getResult() { return numberA + numberB; } }; class subOperation :public Operation { double getResult() { return numberA - numberB; } }; class mulOperation :public Operation { double getResult() { return numberA*numberB; } }; class divOperation :public Operation { double getResult() { return numberA / numberB; } }; class operFactory //实现调用改革吃哦啊做 { public: static Operation *createOperation(char c) { switch (c) { case '+': return new addOperation; break; case '-': return new subOperation; break; case '*': return new mulOperation; break; case '/': return new divOperation; break; } } }; int mainV() { Operation *oper = operFactory::createOperation('-'); oper->numberA = 9; oper->numberB = 99; cout << oper->getResult() << endl; cin.get(); return 0; }

    代理模式

    #include <iostream>
    #include <string>
    using namespace std;
    //代理模式:代理模式给某一个对象提供一个代理对象。
    //并由代理对象控制对源对象的引用。
    //代理就是一个人或一个机构代表还有一个人或者一个机构採取行动。

    //某些情况下。客户不想或者不可以直接引用一个对象, //代理对象可以在客户和目标对象直接起到中介的作用。 //client分辨不出代理主题对象与真实主题对象。 //代理模式可以并不知道真正的被代理对象, //而只持有一个被代理对象的接口,这时候代理对象不可以创建被代理对象。 //被代理对象必须有系统的其它角色代为创建并传入。 //跟MM在网上聊天,一开头总是“hi, 你好”, //“你从哪儿来呀?”“你多大了?”“身高多少呀?” //这些话,真烦人,写个程序做为我的Proxy吧, //凡是接收到这些话都设置好了自己的回答, //接收到其它的话时再通知我回答,怎么样。酷吧。 class SchoolGirl { public: string name; }; class IGiveGift { public: virtual void giveDolls() = 0; virtual void giveFlowers() = 0; }; class Pursuit :public IGiveGift { private: SchoolGirl mm; public: Pursuit(SchoolGirl m) { mm = m; } void giveDolls() { cout << mm.name << " 送你娃娃" << endl; } void giveFlowers() { cout << mm.name << " 送你鲜花" << endl; } }; class Proxy :public IGiveGift { private: Pursuit gg; public: Proxy(SchoolGirl mm) :gg(mm) { //gg=g; } void giveDolls() { gg.giveDolls(); } void giveFlowers() { gg.giveFlowers(); } }; int mai12312321n() { SchoolGirl lijiaojiao; lijiaojiao.name = "李娇娇"; Pursuit zhuojiayi(lijiaojiao); Proxy daili(lijiaojiao); daili.giveDolls(); cin.get(); return 0; }

    单例模式

    #include <iostream>
    #include <string>
    using namespace std;
    //单例模式:单例模式确保某一个类仅仅有一个实例,
    //并且自行实例化并向整个系统提供这个实例单例模式
    //。单例模式仅仅应在有真正的“单一实例”的需求时才可使用。

    //俺有6个美丽的老婆,她们的老公都是我, //我就是我们家里的老公Sigleton。她们仅仅要说道“老公”, //都是指的同一个人。那就是我(刚才做了个梦啦。哪有这么好的事)。

    //#define public private class { public: protected: private: }a1; class Singleton { private: int i; static Singleton *instance; Singleton(int i) { this->i = i; } public: static Singleton *getInstance() { return instance; } void show() { cout << i << endl; } }; Singleton* Singleton::instance = new Singleton(8899); class A :public Singleton { }; int mainJ() { Singleton *s = Singleton::getInstance(); Singleton *s2 = A::getInstance(); cout << (s == s2) << endl; cin.get(); return 0; }

    迭代器模式

    #include <iostream>
    #include <string>
    using namespace std;
    //迭代子模式:迭代子模式能够顺序訪问一个聚集中的元素而不必暴露聚集的内部表象。
    //多个对象聚在一起形成的整体称之为聚集,聚集对象是能够包容一组对象的容器对象。
    //迭代子模式将迭代逻辑封装到一个独立的子对象中,从而与聚集本身隔开。
    //迭代子模式简化了聚集的界面。
    //每个聚集对象都能够有一个或一个以上的迭代子对象。
    //每个迭代子的迭代状态能够是彼此独立的。
    //迭代算法能够独立于聚集角色变化。
    //我爱上了Mary,不顾一切的向她求婚。

    Mary: //“想要我跟你结婚,得答应我的条件” 我:“什么条件我都答应,你说吧” //Mary:“我看上了那个一克拉的钻石” 我:“我买。我买,还有吗?” //Mary:“我看上了湖边的那栋别墅” 我:“我买,我买。还有吗?” //Mary:“我看上那辆法拉利跑车” 我脑袋嗡的一声,坐在椅子上。一咬牙: //“我买。我买。还有吗?” …… class Iterator; class Aggregate { public: virtual Iterator *createIterator() = 0; }; class Iterator { public: virtual void first() = 0; virtual void next() = 0; virtual bool isDone() = 0; virtual bool isDoneA() = 0; //virtual bool isDoneA() = 0; }; class ConcreteAggregate :public Iterator { public: void first() { } void next() { } bool isDone() { } virtual bool isDoneA() { } }; int main12323I() { cin.get(); return 0; }


    訪问者模式

    #include <iostream>
    #include <list>
    #include <string>
    using namespace std;
    //訪问者模式:訪问者模式的目的是封装一些施加于某种数据结构元素之上的操作。
    //一旦这些操作须要改动的话,接受这个操作的数据结构能够保持不变。
    //訪问者模式适用于数据结构相对未定的系统,
    //它把数据结构和作用于结构上的操作之间的耦合解脱开,
    //使得操作集合能够相对自由的演化。訪问者模式使得添加新的操作变的非常easy,
    //就是添加一个新的訪问者类。
    //訪问者模式将有关的行为集中到一个訪问者对象中,
    //而不是分散到一个个的节点类中。

    当使用訪问者模式时, //要将尽可能多的对象浏览逻辑放在訪问者类中。而不是放到它的子类中。 //訪问者模式能够跨过几个类的等级结构訪问属于不同的等级结构的成员类。 //情人节到了,要给每一个MM送一束鲜花和一张卡片, //但是每一个MM送的花都要针对她个人的特点,每张卡片也要依据个人的特点来挑, //我一个人哪搞得清楚,还是找花店老板和礼品店老板做一下Visitor, //让花店老板依据MM的特点选一束花。让礼品店老板也依据每一个人特点选一张卡, //这样就轻松多了。

    //訪问者模式不须要改变基类。不依赖虚函数, class Person { public: char * action; virtual void getConclusion() { }; }; class Man :public Person { public: void getConclusion() { if (action == "成功") { cout << "男人成功时。背后多半有一个伟大的女人。

    " << endl; } else if (action == "恋爱") { cout << "男人恋爱时,凡事不懂装懂。" << endl; } } }; class Woman :public Person { public: void getConclusion() { if (action == "成功") { cout << "女人成功时,背后多半有失败的男人。" << endl; } else if (action == "恋爱") { cout << "女人恋爱时。遇到事懂也装不懂。" << endl; } } }; int main132123() { list<Person*> persons; Person *man1 = new Man(); man1->action = "成功"; persons.push_back(man1); Person *woman1 = new Woman(); woman1->action = "成功"; persons.push_back(woman1); Person *man2 = new Man(); man2->action = "恋爱"; persons.push_back(man2); Person *woman2 = new Woman(); woman2->action = "恋爱"; persons.push_back(woman2); list<Person*>::iterator iter = persons.begin(); while (iter != persons.end()) { (*iter)->getConclusion(); ++iter; } cin.get(); return 0; }


    观察者模式

    #include <iostream>
    #include <string>
    #include <list>
    using namespace std;
    
    //观察者模式:观察者模式定义了一种一队多的依赖关系,
    //让多个观察者对象同一时候监听某一个主题对象。
    //这个主题对象在状态上发生变化时。会通知全部观察者对象,
    //使他们能够自己主动更新自己。

    //想知道咱们公司最新MM情报吗?添加公司的MM情报邮件组即可了。 //tom负责搜集情报,他发现的新情报不用一个一个通知我们。 //直接公布给邮件组。我们作为订阅者(观察者)就能够及时收到情报啦。 // 监视,观察者,都有一个基类,派生,实现不同的效果 //监视者的类,管理全部的观察者,添加或者删除,发出消息。让观察者处理 //观察者的类须要接受消息并处理 class Subject; //能够使用subject class Observer { protected: string name; Subject *sub; public: Observer(string name, Subject *sub)//观察者的名字, 监视与通知的类 { this->name = name;//输入名字 this->sub = sub;//设置谁来通知我 } virtual void update() = 0;//纯虚函数 }; class StockObserver :public Observer //继承,自己实现刷新函数 { public: StockObserver(string name, Subject *sub) :Observer(name, sub) { } void update(); }; class NBAObserver :public Observer { public: NBAObserver(string name, Subject *sub) :Observer(name, sub) { } void update(); }; class Subject // { protected: list<Observer*> observers;///存储观察者的指针。链表 public: string action; virtual void attach(Observer*) = 0; virtual void detach(Observer*) = 0; virtual void notify() = 0;//实现监听的基类 }; class Secretary :public Subject { void attach(Observer *observer) //加载通知的列表 { observers.push_back(observer); } void detach(Observer *observer)//删除 { list<Observer *>::iterator iter = observers.begin(); while (iter != observers.end()) { if ((*iter) == observer) { observers.erase(iter); } ++iter; } } void notify() ///通知函数 { list<Observer *>::iterator iter = observers.begin(); while (iter != observers.end()) { (*iter)->update(); ++iter; } } }; void StockObserver::update() { cout << name << " 收到消息:" << sub->action << endl; if (sub->action == "梁所长来了!") { cout << "我立即关闭股票,装做非常认真工作的样子。" << endl; } if (sub->action == "去喝酒!

    ") { cout << "我立即走" << endl; } } void NBAObserver::update() { cout << name << " 收到消息:" << sub->action << endl; if (sub->action == "梁所长来了!") { cout << "我立即关闭NBA。装做非常认真工作的样子。" << endl; } if (sub->action == "去喝酒。") { cout << "我立即拍" << endl; } } int main123123() { Subject *dwq = new Secretary();//消息监视。监视 Observer *xs = new NBAObserver("xiaoshuai", dwq);//订阅消息 Observer *zy = new NBAObserver("zouyue", dwq); Observer *lm = new StockObserver("limin", dwq); dwq->attach(xs); dwq->attach(zy); dwq->attach(lm);//添加到队列 dwq->action = "去吃饭了!"; dwq->notify(); dwq->action = "去喝酒!"; dwq->notify(); cout << endl; dwq->action = "梁所长来了!"; dwq->notify(); cin.get(); return 0; }

    建造者模式

    #include <string>
    #include <iostream>
    #include <vector>
    using namespace std;
    //建造模式:将产品的内部表象和产品的生成过程切割开来,
    //从而使一个建造过程生成具有不同的内部表象的产品对象。

    //建造模式使得产品内部表象能够独立的变化。 //客户不必知道产品内部组成的细节。 //建造模式能够强制实行一种分步骤进行的建造过程。 //MM最爱听的就是“我爱你”这句话了,见到不同地方的MM, //要能够用她们的方言跟她说这句话哦,我有一个多种语言翻译机, //上面每种语言都有一个按键,见到MM我仅仅要按相应的键, //它就能够用相应的语言说出“我爱你”这句话了, //国外的MM也能够轻松搞掂。这就是我的“我爱你”builder。( //这一定比美军在伊拉克用的翻译机好卖) class Person //抽象类,预留ule接口 { public: virtual void createHead() = 0; virtual void createHand() = 0; virtual void createBody() = 0; virtual void createFoot() = 0; }; class ThinPerson :public Person ///实现抽象类瘦子, { void createHead() { cout << "thin head" << endl; } void createHand() { cout << "thin hand" << endl; } void createBody() { cout << "thin body" << endl; } void createFoot() { cout << "thin foot" << endl; } }; class FatPerson :public Person //胖子 { void createHead() { cout << "fat head" << endl; } void createHand() { cout << "fat hand" << endl; } void createBody() { cout << "fat body" << endl; } void createFoot() { cout << "fat foot" << endl; } }; class Director { private: Person *p;//基类的指针 public: Director(Person *temp) //传递对象 { p = temp;//虚函数实现多态 } void create() { p->createHead(); p->createHand(); p->createBody(); p->createFoot(); } }; //client代码: int mainT() { Person *p = new FatPerson(); Director *d = new Director(p); d->create(); delete d; delete p; cin.get(); return 0; }


    解释器模式

    #include <iostream>
    #include <list>
    #include <string>
    using namespace std;
    //解释器模式:给定一个语言后,解释器模式能够定义出其文法的一种表示,
    //并同一时候提供一个解释器。client能够使用这个解释器来解释这个语言中的句子。

    //解释器模式将描写叙述如何在有了一个简单的文法后。使用模式设计解释这些语句。 //在解释器模式里面提到的语言是指不论什么解释器对象能够解释的不论什么组合。

    //在解释器模式中须要定义一个代表文法的命令类的等级结构, //也就是一系列的组合规则。每个命令对象都有一个解释方法, //代表对命令对象的解释。

    命令对象的等级结构中的对象的不论什么排列组合都是一个语言。

    //俺有一个《泡MM真经》。上面有各种泡MM的攻略。比方说去吃西餐的步骤、 //去看电影的方法等等,跟MM约会时,仅仅要做一个Interpreter, //照着上面的脚本运行就能够了。

    class Context; class AbstractExpression { public: virtual void interpret(Context *) = 0; }; class TerminalExpression :public AbstractExpression { public: void interpret(Context *context) { cout << "终端解释器" << endl; } }; class NonterminalExpression :public AbstractExpression { public: void interpret(Context *context) { cout << "非终端解释器" << endl; } }; class Context { public: string input, output; }; int mainK() { Context *context = new Context(); list<AbstractExpression*> lt; lt.push_back(new TerminalExpression()); lt.push_back(new NonterminalExpression()); lt.push_back(new TerminalExpression()); lt.push_back(new TerminalExpression()); for (list<AbstractExpression*>::iterator iter = lt.begin(); iter != lt.end(); iter++) { (*iter)->interpret(context); } cin.get(); return 0; }

    命令模式

    #include <iostream>
    #include <string>
    #include <list>
    //命令模式:命令模式把一个请求或者操作封装到一个对象中。
    //命令模式把发出命令的责任和运行命令的责任切割开,委派给不同的对象。
    //命令模式同意请求的一方和发送的一方独立开来。
    //使得请求的一方不必知道接收请求的一方的接口,
    //更不必知道请求是怎么被接收。
    //以及操作是否运行,何时被运行以及是怎么被运行的。
    //系统支持命令的撤消。
    //俺有一个MM家里管得特别严,没法见面。仅仅好借助于她弟弟在我们俩之间传送信息,
    //她对我有什么指示。就写一张纸条让她弟弟带给我。这不。
    //她弟弟又传送过来一个COMMAND,为了感谢他,我请他吃了碗杂酱面,
    //哪知道他说:“我同一时候给我姐姐三个男朋友送COMMAND,就数你最小气,
    //才请我吃面。”
    //
    using namespace std;
    
    class Barbecuer  //接收者运行命令
    {
    public:
    	void bakeMutton()
    	{
    		cout << "烤羊肉串" << endl;
    	}
    	void bakeChickenWing()
    	{
    		cout << "烤鸡翅" << endl;
    	}
    };
    
    class Command   //命令基类
    {
    protected:
    	Barbecuer *receiver;//类的包括
    public:
    	Command(Barbecuer *receiver)//命令接受
    	{
    		this->receiver = receiver;
    	}
    	virtual void executeCommand() = 0;
    };
    
    class BakeMuttonCommand :public Command  //命令传送着
    {
    public:
    	BakeMuttonCommand(Barbecuer *receiver) :Command(receiver)
    	{}
    	void executeCommand()
    	{
    		receiver->bakeMutton();
    	}
    };
    
    class BakeChikenWingCommand :public Command  //命令传送着
    {
    public:
    	BakeChikenWingCommand(Barbecuer *receiver) :Command(receiver)
    	{}
    	void executeCommand()
    	{
    		receiver->bakeChickenWing();
    	}
    };
    
    class Waiter        //服务员
    {
    private:
    	Command *command;
    public:
    	void setOrder(Command *command)
    	{
    		this->command = command;
    	}
    	void notify()
    	{
    		command->executeCommand();
    	}
    };
    
    class Waiter2   //gei多个对象下达命令
    {
    private:
    	list<Command*> orders;
    public:
    	void setOrder(Command *command)
    	{
    		orders.push_back(command);
    	}
    	void cancelOrder(Command *command)
    	{}
    	void notify()
    	{
    		list<Command*>::iterator iter = orders.begin();
    		while (iter != orders.end())
    		{
    			(*iter)->executeCommand();
    			iter++;
    		}
    	}
    };
    
    
    int main1232131231()
    {
    
    	Barbecuer *boy = new Barbecuer();
    	Command *bm1 = new BakeMuttonCommand(boy);
    	Command *bm2 = new BakeMuttonCommand(boy);
    	Command *bc1 = new BakeChikenWingCommand(boy);
    
    	Waiter2 *girl = new Waiter2();
    
    	girl->setOrder(bm1);
    	girl->setOrder(bm2);
    	girl->setOrder(bc1);
    
    	girl->notify();
    
    
    	cin.get();
    
    	return 0;
    }

    模板模式

    #include<iostream>
    #include <vector>
    #include <string>
    using namespace std;
    /*模板方法模式:模板方法模式准备一个抽象类。
    将部分逻辑以详细方法以及详细构造子的形式实现,
    然后声明一些抽象方法来迫使子类实现剩余的逻辑。
    不同的子类能够以不同的方式实现这些抽象方法,
    从而对剩余的逻辑有不同的实现。

    先制定一个顶级逻辑框架, 而将逻辑的细节留给详细的子类去实现。 女生从认识到得手的不变的步骤分为巧遇、打破僵局、展开追求、接吻、得手 但每一个步骤针对不同的情况。都有不一样的做法,这就要看你随机应变啦(详细实现)*/ class AbstractClass { public: void Show() { cout << "我是" << GetName() << endl; } protected: virtual string GetName() = 0; }; class Naruto : public AbstractClass { protected: virtual string GetName() { return "火影史上最帅的六代目---一鸣惊人naruto"; } }; class OnePice : public AbstractClass { protected: virtual string GetName() { return "我是无恶不做的大海贼---路飞"; } }; //client int mainP13() { Naruto* man = new Naruto(); man->Show(); OnePice* man2 = new OnePice(); man2->Show(); cin.get(); return 0; }

    桥接模式

    #include <iostream>
    #include <string>
    using namespace std;
    //桥梁模式:将抽象化与实现化脱耦。使得二者能够独立的变化。
    //也就是说将他们之间的强关联变成弱关联。
    //也就是指在一个软件系统的抽象化和实现化之间使用组合 
    /// 聚合关系而不是继承关系,从而使两者能够独立的变化。
    //早上碰到MM。要说早上好。晚上碰到MM,要说晚上好;
    //碰到MM穿了件新衣服。要说你的衣服好美丽哦,碰到MM新做的发型。
    //要说你的头发好美丽哦。不要问我“早上碰到MM新做了个发型怎么说”
    //这样的问题。自己用BRIDGE组合一下不即可了。

    class HandsetSoft { public: virtual void run() = 0; }; class HandsetGame :public HandsetSoft { public: void run() { cout << "执行手机游戏" << endl; } }; class HandsetAddressList :public HandsetSoft { public: void run() { cout << "执行手机通讯录" << endl; } }; class HandsetBrand { protected: HandsetSoft *soft; public: void setHandsetSoft(HandsetSoft *soft) { this->soft = soft; } virtual void run() = 0; }; class HandsetBrandN :public HandsetBrand { public: void run() { soft->run(); } }; class HandsetBrandM :public HandsetBrand { public: void run() { soft->run(); } }; int mainS() { HandsetBrand *hb; hb = new HandsetBrandM(); hb->setHandsetSoft(new HandsetGame()); hb->run(); hb->setHandsetSoft(new HandsetAddressList()); hb->run(); cin.get(); return 0; }


    适配器模式

    #include <iostream>
    #include <string>
    using namespace std;
    //适配器(变压器)模式:把一个类的接口变换成client所期待的还有一种接口
    //。从而使原本因接口原因不匹配而无法一起工作的两个类能够一起工作。
    //适配类能够依据參数返还一个合适的实例给client。
    //
    //在朋友聚会上碰到了一个美女Sarah,从香港来的。
    //可我不会说粤语。她不会说普通话,仅仅好求助于我的朋友kent了,
    //他作为我和Sarah之间的Adapter,让我和Sarah能够相互交谈了
    //(也不知道他会不会耍我)。

    class Player { public: string name; Player(string name) { this->name = name; } virtual void attack() = 0; virtual void defence() = 0; }; class Forwards :public Player { public: Forwards(string name) :Player(name){} void attack() { cout << name << " 前锋进攻" << endl; } void defence() { cout << name << " 前锋防守" << endl; } }; class Center :public Player { public: Center(string name) :Player(name){} void attack() { cout << name << " 中锋进攻" << endl; } void defence() { cout << name << " 中锋防守" << endl; } }; class Backwards :public Player { public: Backwards(string name) :Player(name){} void attack() { cout << name << " 后卫进攻" << endl; } void defence() { cout << name << " 后卫防守" << endl; } }; /*****************************************************************/ class ForeignCenter { public: string name; ForeignCenter(string name) { this->name = name; } void myAttack() { cout << name << " 外籍中锋进攻" << endl; } void myDefence() { cout << name << " 外籍后卫防守" << endl; } }; /*****************************************************************/ class Translator :public Player { private: ForeignCenter *fc; public: Translator(string name) :Player(name) { fc = new ForeignCenter(name); } void attack() { fc->myAttack(); } void defence() { fc->myDefence(); } }; /*****************************************************************/ int mainM() { Player *p1 = new Center("李俊宏"); p1->attack(); p1->defence(); Translator *tl = new Translator("姚明"); tl->attack(); tl->defence(); cin.get(); return 0; }


    外观模式

    #include <iostream>
    #include <string>
    using namespace std;
    //门面模式:外部与一个子系统的通信必须通过一个统一的门面对象进行。
    //门面模式提供一个高层次的接口,使得子系统更易于使用。
    //每个子系统仅仅有一个门面类,并且此门面类仅仅有一个实例,
    //也就是说它是一个单例模式。但整个系统能够有多个门面类。

    // //我有一个专业的Nikon相机,我就喜欢自己手动调光圈、快门, //这样照出来的照片才专业,但MM可不懂这些。教了半天也不会。 //幸好相机有Facade设计模式。把相机调整到自己主动档, //仅仅要对准目标按快门即可了,一切由相机自己主动调整, //这样MM也能够用这个相机给我拍张照片了。 class Sub1 { public: void f1() { cout << "子系统的方法 1" << endl; } }; class Sub2 { public: void f2() { cout << "子系统的方法 2" << endl; } }; class Sub3 { public: void f3() { cout << "子系统的方法 3" << endl; } }; class Facade { private: Sub1 *s1; Sub2 *s2; Sub3 *s3; public: Facade() { s1 = new Sub1(); s2 = new Sub2(); s3 = new Sub3(); } void method() { s1->f1(); s2->f2(); s3->f3(); } }; int mainB () { Facade *f = new Facade(); f->method(); cin.get(); return 0; }

    享元模式

    #include <iostream>
    #include <list>
    #include <string>
    #include <map>
    using namespace std;
    
    //享元模式:FLYWEIGHT在拳击比赛中指最轻量级。
    //享元模式以共享的方式高效的支持大量的细粒度对象。

    //享元模式能做到共享的关键是区分内蕴状态和外蕴状态。

    //内蕴状态存储在享元内部。不会随环境的改变而有所不同。 //外蕴状态是随环境的改变而改变的。外蕴状态不能影响内蕴状态, //它们是相互独立的。将能够共享的状态和不能够共享的状态从常规类中区分开来, //将不能够共享的状态从类里剔除出去。client不能够直接创建被共享的对象。 //而应当使用一个工厂对象负责创建被共享的对象。 //享元模式大幅度的减少内存中对象的数量。 // //每天跟MM发短信。手指都累死了,近期买了个新手机, //能够把一些经常使用的句子存在手机里,要用的时候,直接拿出来 //。在前面加上MM的名字就能够发送了,再不用一个字一个字敲了。

    //共享的句子就是Flyweight。MM的名字就是提取出来的外部特征。 //依据上下文情况使用。 class WebSite { public: virtual void use() = 0;//预留接口实现功能 }; class ConcreteWebSite :public WebSite { private: string name; public: ConcreteWebSite(string name)//实例化 { this->name = name; } void use() { cout << "站点分类: " << name << endl; } }; class WebSiteFactory { private: map<string, WebSite*> wf; public: WebSite *getWebSiteCategory(string key) { if (wf.find(key) == wf.end()) { wf[key] = new ConcreteWebSite(key); } return wf[key]; } int getWebSiteCount() { return wf.size(); } }; int main123qweqe() { WebSiteFactory *wf = new WebSiteFactory(); WebSite *fx = wf->getWebSiteCategory("good"); fx->use(); WebSite *fy = wf->getWebSiteCategory("产品展示"); fy->use(); WebSite *fz = wf->getWebSiteCategory("产品展示"); fz->use(); WebSite *f1 = wf->getWebSiteCategory("博客"); f1->use(); WebSite *f2 = wf->getWebSiteCategory("博客"); f2->use(); cout << wf->getWebSiteCount() << endl; cin.get(); return 0; }


    原型模式

    #include <iostream>
    #include <string>
    using namespace std;
    //原型模式同意动态的添加或降低产品类,
    //产品类不须要非得有不论什么事先确定的等级结构,
    //原始模型模式适用于不论什么的等级结构。
    //缺点是每个类都必须配备一个克隆方法。
    
    
    //跟MM用QQ聊天,一定要说些深情的话语了,
    //我搜集了好多肉麻的情话,须要时仅仅要copy出来放到QQ里面即可了。
    //这就是我的情话prototype了。
    //原型模式:通过给出一个原型对象来指明所要创建的对象的类型,
    //然后用复制这个原型对象的方法创建出很多其它同类型的对象。
    
    class Resume
    {
    private:
    	string name, sex, age, timeArea, company;
    public:
    	Resume(string s)
    	{
    		name = s;
    	}
    	void setPersonalInfo(string s, string a)
    	{
    		sex = s;
    		age = a;
    	}
    	void setWorkExperience(string t, string c)
    	{
    		timeArea = t;
    		company = c;
    	}
    	void display()
    	{
    		cout << name << "  " << sex << "  " << age << endl;
    		cout << "工作经历:  " << timeArea << "  " << company << endl << endl;
    
    	}
    	Resume *clone()
    	{
    		Resume *b;
    		b = new Resume(name);
    		b->setPersonalInfo(sex, age);
    		b->setWorkExperience(timeArea, company);
    		return b;
    	}
    };
    
    
    int main213123()
    {
    	Resume *r = new Resume("李彦宏");
    	r->setPersonalInfo("男", "30");
    	r->setWorkExperience("2007-2010", "读研究生");
    	r->display();
    
    
    	Resume *r2 = r->clone();
    	r2->setWorkExperience("2003-2007", "读本科");
    
    	r->display();
    	r2->display();
    
    	cin.get();
    	return 0;
    }

    责任链模式

    #include<iostream>
    #include <string>
    using namespace std;
    
    //责任链模式:在责任链模式中,非常多对象由每个对象对其下家的引用而接起来形成
    //一条链。请求在这个链上传递,直到链上的某一个对象决定处理此请求。
    //客户并不知道链上的哪一个对象终于处理这个请求。系统能够在不影响client的
    //情况下动态的又一次组织链和分配责任。

    处理者有两个选择:承担责任或者把责任 //推给下家。一个请求能够终于不被不论什么接收端对象所接受。 // //晚上去上英语课。为了好开溜坐到了最后一排。哇,前面坐了好几个美丽的MM哎, //找张纸条。写上“Hi, 能够做我的女朋友吗?假设不愿意请向前传”。 //纸条就一个接一个的传上去了。糟糕,传到第一排的MM把纸条传给老师了, //听说是个老处女呀,快跑! class Request //请求 { public: string requestType; string requestContent; int number; }; class Manager ///管理者 { protected: string name; Manager *superior; public: Manager(string name) { this->name = name; } void setSuperior(Manager *superior) { this->superior = superior; } virtual void requestApplications(Request *request) = 0; }; class CommonManager :public Manager //经理 { public: CommonManager(string name) :Manager(name) {} void requestApplications(Request *request) { if (request->requestType == "请假" && request->number <= 2) { cout << name << " " << request->requestContent << " 数量: " << request->number << "被批准" << endl; } else { if (superior != NULL) { superior->requestApplications(request); } } } }; class Majordomo :public Manager //总监 { public: Majordomo(string name) :Manager(name) {} void requestApplications(Request *request) { if (request->requestType == "请假" && request->number <= 5) { cout << name << " " << request->requestContent << " 数量: " << request->number << "被批准" << endl; } else { if (superior != NULL) { superior->requestApplications(request); } } } }; class GeneralManager :public Manager //总经理 { public: GeneralManager(string name) :Manager(name) {} void requestApplications(Request *request) { if (request->requestType == "请假") { cout << name << " " << request->requestContent << " 数量: " << request->number << "被批准" << endl; } } }; int main123213123213() { CommonManager *jinli = new CommonManager("经理"); Majordomo *zongjian = new Majordomo("总监"); GeneralManager *zhongjingli = new GeneralManager("总经理"); jinli->setSuperior(zongjian); zongjian->setSuperior(zhongjingli); Request *request = new Request(); request->requestType = "请假"; request->requestContent = "李俊宏请假"; request->number = 1; jinli->requestApplications(request); request->requestType = "请假"; request->requestContent = "李俊宏请假"; request->number = 4; jinli->requestApplications(request); request->requestType = "请假"; request->requestContent = "李俊宏请假"; request->number = 10; jinli->requestApplications(request); cin.get(); return 0; }


    中介者模式

    #include<iostream>
    #include <string>
    using namespace std;
    ////MEDIATOR 调停者模式
    //
    ////调停者模式:调停者模式包装了一系列对象相互作用的方式。
    //使得这些对象不必相互明显作用。

    从而使他们能够松散偶合。

    //当某些对象之间的作用发生改变时,不会马上影响其它的一些对象之间的作用。 //保证这些作用能够彼此独立的变化。调停者模式将多对多的相互作用转化 //为一对多的相互作用。调停者模式将对象的行为和协作抽象化 //,把对象在小尺度的行为上与其它对象的相互作用分开处理。 // ////四个MM打麻将,相互之间谁应该给谁多少钱算不清楚了, //幸亏当时我在旁边,依照各自的筹码数算钱,赚了钱的从我这里拿, //赔了钱的也付给我,一切就OK啦,俺得到了四个MM的电话。

    // ////中介者模式,找不到老婆能够相亲靠婚介 class Country; class UniteNations { public: virtual void declare(string message, Country *colleague) = 0; }; class Country { protected: UniteNations *mediator; public: Country(UniteNations *mediator) { this->mediator = mediator; } }; class USA :public Country { public: USA(UniteNations *mediator) :Country(mediator) {} void declare(string message) { cout << "美公布信息: " << message << endl; mediator->declare(message, this); } void getMessage(string message) { cout << "美国获得对方信息: " << message << endl; } }; class Iraq :public Country { public: Iraq(UniteNations *mediator) :Country(mediator) {} void declare(string message) { cout << "伊拉克公布信息: " << message << endl; mediator->declare(message, this); } void getMessage(string message) { cout << "伊拉克获得对方信息: " << message << endl; } }; class UnitedNationsSecurityCouncil :public UniteNations { public: USA *usa; Iraq *iraq; void declare(string message, Country *colleague) { if (colleague == usa) { iraq->getMessage(message); } else { usa->getMessage(message); } } }; int mainWERT() { UnitedNationsSecurityCouncil *unsc = new UnitedNationsSecurityCouncil(); USA *c1 = new USA(unsc); Iraq *c2 = new Iraq(unsc); unsc->usa = c1; unsc->iraq = c2; c1->declare("不准开发核武器。否则打你。"); c2->declare("他妈的美国去死!

    "); cin.get(); return 0; }


    装饰模式

    #include <string>
    #include <iostream>
    using namespace std;
    
    //装饰模式:装饰模式以对client透明的方式扩展对象的功能,
    //是继承关系的一个替代方案,提供比继承很多其它的灵活性。

    //动态给一个对象添加功能,这些功能能够再动态的撤消。

    //添加由一些基本功能的排列组合而产生的非常大量的功能。 // //Mary过完轮到Sarly过生日,还是不要叫她自己挑了。 //不然这个月伙食费肯定玩完,拿出我去年在华山顶上照的照片。 //在背面写上“最好的的礼物,就是爱你的Fita”, //再到街上礼品店买了个像框(卖礼品的MM也非常美丽哦), //再找隔壁搞美术设计的Mike设计了一个美丽的盒子装起来……, //我们都是Decorator。终于都在修饰我这个人呀,怎么样。看懂了吗? class Person { private: string m_strName; public: Person(string strName) { m_strName = strName; } Person(){} virtual void show() { cout << "装扮的是:" << m_strName << endl; } }; class Finery :public Person { protected: Person *m_component; public: void decorate(Person* component) { m_component = component; } virtual void show() { m_component->show(); } }; class TShirts :public Finery { public: virtual void show() { m_component->show(); cout << "T shirts" << endl; } }; class BigTrouser :public Finery { public: virtual void show() { m_component->show(); cout << "Big Trouser" << endl; } }; int mainE() { Person *p = new Person("小李"); BigTrouser *bt = new BigTrouser(); TShirts *ts = new TShirts(); bt->decorate(p); ts->decorate(bt); ts->show(); cin.get(); return 0; }


    状态模式

    #include <iostream>
    #include <string>
    using namespace std;
    //状态模式:状态模式同意一个对象在其内部状态改变的时候改变行为。
    //这个对象看上去象是改变了它的类一样。

    状态模式把所研究的对象的行 //为包装在不同的状态对象里,每个状态对象都属于一个抽象状态类的 //一个子类。状态模式的意图是让一个对象在其内部状态改变的时候, //其行为也随之改变。状态模式须要对每个系统可能取得的状态创立一个状态类的 //子类。当系统的状态变化时。系统便改变所选的子类。

    // //跟MM交往时。一定要注意她的状态哦,在不同的状态时她的行为会有不同, //比方你约她今天晚上去看电影。对你没兴趣的MM就会说“有事情啦” //。对你不讨厌但还没喜欢上的MM就会说“好啊,只是能够带上我同事么?” //,已经喜欢上你的MM就会说“几点钟?看完电影再去泡吧怎么样?”, //当然你看电影过程中表现良好的话。也能够把MM的状态从不讨厌不喜欢变成喜欢哦。

    class Work; class State; class ForenonnState; class State { public: virtual void writeProgram(Work*) = 0;//准柜台的基类,抽象类 }; class Work //实施工作的类。依据状态运行不同的操作 { public: int hour; State *current; Work(); void writeProgram() { current->writeProgram(this); } }; class EveningState :public State //晚上状态 { public: void writeProgram(Work *w) { cout << "当前时间: " << w->hour << "心情非常好,在看《明朝那些事儿》。收获非常大!" << endl; } }; class AfternoonState :public State { public: void writeProgram(Work *w) { if (w->hour < 19) { cout << "当前时间: " << w->hour << "下午午睡后。工作还是精神百倍!" << endl; } else { w->current = new EveningState(); w->writeProgram(); } } }; class ForenonnState :public State { public: void writeProgram(Work *w) { if (w->hour < 12) { cout << "当前时间: " << w->hour << "上午工作精神百倍!" << endl; } else { w->current = new AfternoonState(); w->writeProgram(); } } }; Work::Work() { current = new ForenonnState(); } int mainD() { Work *w = new Work(); w->hour = 21; w->writeProgram(); cin.get(); return 0; }

    组合模式

    #include <iostream>
    #include <vector>
    #include <string>
    using namespace std;
    //合成模式:合成模式将对象组织到树结构中,能够用来描写叙述总体与部分的关系。

    //合成模式就是一个处理对象的树结构的模式。合成模式把部分与总体的关系用树结构表示出来。 //合成模式使得client把一个个单独的成分对象和由他们复合而成的合成对象同等看待。

    // //Mary今天过生日。

    “我过生日,你要送我一件礼物。

    ” //嗯,好吧。去商店。你自己挑。

    ” //“这件T恤挺美丽,买,这条裙子好看。买,这个包也不错。买 //。

    ”“喂,买了三件了呀,我仅仅答应送一件礼物的哦。

    //”“什么呀。T恤加裙子加包包。正好配成一套呀,小姐,麻烦你包起来。 //”“……”。MM都会用Composite模式了,你会了没有? class Component { public: string name; Component(string name) { this->name = name; } virtual void add(Component *) = 0; virtual void remove(Component *) = 0; virtual void display(int) = 0; }; class Leaf :public Component { public: Leaf(string name) :Component(name) {} void add(Component *c) { cout << "leaf cannot add" << endl; } void remove(Component *c) { cout << "leaf cannot remove" << endl; } void display(int depth) { string str(depth, '-'); str += name; cout << str << endl; } }; class Composite :public Component { private: vector<Component*> component; public: Composite(string name) :Component(name) {} void add(Component *c) { component.push_back(c); } void remove(Component *c) { vector<Component*>::iterator iter = component.begin(); while (iter != component.end()) { if (*iter == c) { component.erase(iter); } iter++; } } void display(int depth) { string str(depth, '-'); str += name; cout << str << endl; vector<Component*>::iterator iter = component.begin(); while (iter != component.end()) { (*iter)->display(depth + 2); iter++; } } }; int main() { Component *p = new Composite("小李"); p->add(new Leaf("小王")); p->add(new Leaf("小强")); Component *sub = new Composite("小虎"); sub->add(new Leaf("小王")); sub->add(new Leaf("小明")); sub->add(new Leaf("小柳")); p->add(sub); p->display(0); cout << "*******" << endl; sub->display(2); cin.get(); return 0; }



  • 相关阅读:
    Java中的Set List HashSet互转
    Java数组如何转为List集合
    Map
    Jave中的日期
    mybatis plus 条件构造器queryWrapper学习
    Error running 'JeecgSystemApplication': Command line is too long. Shorten command line for JeecgSystemApplication or also for Spring Boot default configuration.
    RBAC权限系统分析、设计与实现
    html拼接时onclick事件传递json对象
    PostgreSQL 大小写问题 一键修改表名、字段名为小写 阅读模式
    openssl创建的自签名证书,使用自签发证书--指定使用多域名、泛域名及直接使用IP地址
  • 原文地址:https://www.cnblogs.com/yxysuanfa/p/7159278.html
Copyright © 2020-2023  润新知