/* http://blog.csdn.net/lcl_data/article/details/12117349 按照目的來分,設計模式能夠分爲建立型模式、結構型模式和行爲型模式。5+7+11=23 【建立型模】式用來處理對象的建立過程;結構型模式用來處理類或者對象的組合;行爲型模式用來對類或對象怎樣交互和怎樣分配職責進行描述。 建立型模式用來處理對象的建立過程,主要包含如下5種設計模式: 1,工廠方法模式(Factory Method Pattern)的用意是定義一個建立產品對象的工廠接口,將實際建立工做推遲到子類中。 經典例子: 2,抽象工廠模式(Abstract Factory Pattern)的意圖是提供一個建立一系列相關或者相互依賴的接口,而無需指定它們具體的類。 經典例子: 3,建造者模式(Builder Pattern)的意圖是將一個複雜的構建與其表示相分離,使得一樣的構建過程能夠建立不一樣的表示。 經典例子: 胖瘦人 4,原型模式(Prototype Pattern)是用原型實例指定建立對象的種類,而且經過拷貝這些原型建立新的對象。 經典例子: 5,單例模式(Singleton Pattern)是保證一個類僅有一個實例,並提供一個訪問它的全局訪問點。 【結構型模式】用來處理類或者對象的組合,主要包含如下7種設計模式: 6,適配器模式(Adapter Pattern)是將一個類的接口轉換成客戶但願的另一個接口。使得本來因爲接口不兼容而不能一塊兒工做的那些類能夠一塊兒工做。 經典例子: 7,橋接模式(Bridge Pattern)是將抽象部分與實際部分分離,使它們均可以獨立的變化。 經典例子: 8,組合模式(Composite Pattern)是將對象組合成樹形結構以表示「部分--總體」的層次結構。使得用戶對單個對象和組合對象的使用具備一致性。 經典例子: 書店與網上書店 汽車奇瑞 9,裝飾者模式(Decorator Pattern)動態的給一個對象添加一些額外的職責。就增長功能來講,此模式比生成子類更爲靈活。 經典例子: 10,外觀模式(Facade Pattern)是爲子系統中的一組接口提供一個一致的界面,此模式定義了一個高層接口,這個接口使得這一子系統更加容易使用。 經典例子: 11,享元模式(Flyweight Pattern)是以共享的方式高效的支持大量的細粒度的對象。 經典例子: 12,代理模式(Proxy Pattern)就是爲其餘對象提供一種代理以控制對這個對象的訪問。 經典例子: 【行爲型模式】用來對類或對象怎樣交互和怎樣分配職責進行描述,主要包含如下11種設計模式: 13,責任鏈模式(Chain of Responsibility Pattern)每個對象對其下家的引用而鏈接起來造成一條鏈。請求在這個鏈上傳遞,直處處理此請求,在不影響客戶端的狀況下動態處理。 經典例子: 多經理處理加薪 14,命令模式(Command Pattern)是將一個請求封裝爲一個對象,從而使你可用不一樣的請求對客戶端進行參數化;對請求排隊或記錄請求日誌,以及支持可撤銷的操做。 經典例子: 服務員下單 15,解釋器模式(Interpreter Pattern)就是描述瞭如何爲簡單的語言定義一個語法,如何在該語言中表示一個句子,以及如何解釋這些句子。 經典例子: 16,迭代器模式(Iterator Pattern)是提供了一種方法順序來訪問一個聚合對象中的各個元素,而又不須要暴露該對象的內部表示。 經典例子: 17,中介者模式(Mediator Pattern)定義一箇中介對象來封裝系列對象之間的交互。終結者使各個對象不須要顯示的相互調用 從而使其耦合性鬆散,並且能夠獨立的改變他們之間的交互。 經典例子: 18,備忘錄模式(Memento Pattern)是在不破壞封裝的前提下,捕獲一個對象的內部狀態,並在該對象以外保存這個狀態。 經典例子: 遊戲備份 19,觀察者模式(Observer Pattern)定義對象間的一種一對多的依賴關係,當一個對象的狀態發生改變時,全部依賴於它的對象都獲得通知並被自動更新。 經典例子: 終端解釋器 20,狀態模式(State Pattern)就是容許一個對象在其內部狀態改變時改變它的行爲,使對象看起來彷佛修改了它的類。 經典例子: 工人白天工做晚上睡覺 21,策略模式(Strategy Pattern)就是準備一組算法,並將每個算法封裝起來,使得它們能夠互換。 經典例子: 殺手與武器 22,模板方法模式(Template Method Pattern)使得子類能夠不改變一個算法的結構便可重定義該算法的某些特定步驟。 經典例子: 咖啡與茶 23,訪問者模式(Visitor Pattern)就是表示一個做用於某對象結構中的各元素的操做,它使你能夠在不改變各元素的類的前提下定義做用於這些元素的新操做。 經典例子: 畫線 收錄狀況 建立型模式: 1 2 3 4 5 結構型模式: 6 7 8 9 10 11 12 行爲型模式: 11 12 13 14 15 16 17 18 19 20 21 22 23 */ #include <bits/stdc++.h> using namespace std; class Builder { public: virtual void BuildHead() {} virtual void BuildBody() {} virtual void Buildleg(){} }; //構造瘦人 class ThinBuilder : public Builder { public: void BuildHead() { cout<<"build thin body"<<endl; } void BuildBody() { cout<<"build thin head"<<endl; } void Buildleg() { cout<<"build thin leg"<<endl; } }; //構造胖人 class FatBuilder : public Builder { public: void BuildHead() { cout<<"build fat body"<<endl; } void BuildBody() { cout<<"build fat head"<<endl; } void Buildleg() { cout<<"build fat leg"<<endl; } }; //構造的指揮官 class Director { private: Builder *m_pBuilder; public: Director(Builder *builder) { m_pBuilder = builder; } void Create(){ m_pBuilder->BuildHead(); m_pBuilder->BuildBody(); m_pBuilder->Buildleg(); } }; void test3() { FatBuilder thin; Director director(&thin); director.Create(); cout << "http://blog.csdn.net/wuzhekai1985/article/details/6667467" << endl; } class CPrototype { public: CPrototype(){} virtual ~CPrototype(){} virtual CPrototype* Clone() = 0; }; //實現 class CConcretePrototype : public CPrototype { public: CConcretePrototype():m_counter(0){} virtual ~CConcretePrototype(){} //拷貝構造函數 CConcretePrototype(const CConcretePrototype& rhs) { m_counter = rhs.m_counter; } //複製自身 virtual CPrototype* Clone() { //調用拷貝構造函數 return new CConcretePrototype(*this); } private: int m_counter; }; void test4() { CPrototype* conProA = new CConcretePrototype();//生成對像 CPrototype* conProB = conProA->Clone(); //複製自身 delete conProA; conProA=NULL; delete conProB; conProB=NULL; cout << "http://blog.csdn.net/cabinriver/article/details/8895372/" << endl; cout <<"more: http://blog.csdn.net/lcl_data/article/details/8764228" << endl; } class Singleton { public: static Singleton *GetInstance(){return m_Instance;} int GetTest(){ return m_Test;} private: Singleton(){ m_Test = 10; } static Singleton *m_Instance; int m_Test; class GC { public : ~GC() { if (m_Instance != NULL ) { cout<< "Here is the test" <<endl; delete m_Instance; m_Instance = NULL ; } } }; static GC gc; }; Singleton *Singleton ::m_Instance = new Singleton(); Singleton ::GC Singleton ::gc; void test5() { Singleton *singletonObj = Singleton ::GetInstance(); cout<<singletonObj->GetTest()<<endl; cout<<"http://www.jellythink.com/archives/82"<<endl; } /****************************************************************************/ class Target { public: virtual void Request(){}; }; class Adaptee { public: void SpecificRequest() { cout<<"Called SpecificRequest()"<<endl; } }; class Adapter : public Adaptee, public Target { public: void Request(){this->SpecificRequest();} }; void test6() { Target *t = new Adapter(); t->Request(); } /****************************************************************************/ class Implementor { public: virtual void Show() {} }; class Implementor1:public Implementor { public: virtual void Show() { cout<<"Implementor1 is showing..."<<endl; } }; class Implementor2: public Implementor { public: virtual void Show() { cout<<"Implementor2 is showing.."<<endl; } }; class Abstractor { Implementor *_implementor; public: virtual void SetImplementor(Implementor* ot) { this->_implementor = ot; } virtual void operate() { _implementor->Show(); } }; class RefinedAbstractor:public Abstractor { }; void test7() { Implementor1 * im1 = new Implementor1(); Implementor2 * im2 = new Implementor2(); RefinedAbstractor *re = new RefinedAbstractor(); re->SetImplementor(im1); re->operate(); re->SetImplementor(im2); re->operate(); } /****************************************************************************/ class Shop { public: virtual void sell() = 0; }; class BookShop: public Shop { public: virtual void sell() { cout << "sell book" << endl; } }; class NetShop: public Shop { public: NetShop() { m_shop = new BookShop(); } virtual void sell() { discount(); m_shop->sell(); } void discount() { cout << "discount ++" << endl; } private: Shop* m_shop; }; void test8() { NetShop* netShop = new NetShop; netShop->sell(); } class Car { public: virtual void CreatPartA() = 0; virtual void CreatPartB() = 0; }; class DazhongCar :public Car { public: virtual void CreatPartA() { cout <<endl<<"大衆:"<<endl<< "大衆A部分" << endl; } virtual void CreatPartB() { cout << "大衆B部分" << endl; } }; class Qirui :public Car { public: virtual void CreatPartA() { cout << endl << "奇瑞:" << endl << "奇瑞A部分" << endl; } virtual void CreatPartB() { cout << "奇瑞車B部分" << endl; } }; class Direct //指揮者類 { public: Direct(Car*Temp) { C = Temp; } void Create() { C->CreatPartA(); C->CreatPartB(); } private: Car*C; }; void test88( ) { Car*D = new DazhongCar; Car*Q = new Qirui; Direct *A = new Direct(D); Direct *B = new Direct(Q); A->Create(); B->Create(); } class Parser { public: void Parse() { cout<<"語法分析"<<endl; } }; class GenMachineCode { public: void GenCode() { cout<<"產生機器碼"<<endl;} }; //高層接口 Fecade class Compiler { public: void Run() { Parser parser; parser.Parse(); GenMachineCode genMacCode; genMacCode.GenCode(); } }; void test10() { Compiler compiler; compiler.Run(); } #include<bits/stdc++.h> using namespace std; class Flyweight { private: //內部狀態 string intrinsic; protected: //外部狀態 const string extrainsic; public: Flyweight(string _ex) :extrainsic ( _ex) { } //定義業務操做 virtual void operate(){} string getIntrinsic() { return intrinsic; } void setIntrinsic(string _in) { intrinsic = _in; } }; class ConcreteFlyweight1 :public Flyweight { public: ConcreteFlyweight1(string ex) :Flyweight(ex) {} void operate() { //根據外部邏輯進行業務處理 cout << "1根據外部邏輯進行業務處理!" << endl; } }; class ConcreteFlyweight2 :public Flyweight { public: ConcreteFlyweight2(string ex) :Flyweight(ex) {} void operate() { //根據外部邏輯進行業務處理 cout << "2根據外部邏輯進行業務處理!" << endl; } }; class FlyweightFactory { private: static map<string, Flyweight*> pool; public: Flyweight* getFlyweight(string ex) { map<string, Flyweight*>::iterator it = pool.find(ex); if (it == pool.end()) { cout << "Creat Flyweight1" << endl; pool[ex] = new ConcreteFlyweight1(ex); } return pool[ex]; } }; map<string, Flyweight*> FlyweightFactory::pool = map<string,Flyweight*>(); void test11() { //http://www.cnblogs.com/lang5230/archive/2016/04/09/5371284.html FlyweightFactory ff; Flyweight * bd = ff.getFlyweight("wz"); Flyweight * db= ff.getFlyweight("wz"); bd->operate();db->operate(); cout<<bd<<"======"<<db<<endl; } class Subject{ public: virtual void SellBooks()=0; }; class RealBookShop : public Subject{ public: void SellBooks(){ cout<<"sell books!"<<endl; } }; class Taobao_proxy : public Subject{ public: Taobao_proxy(RealBookShop* realshop){ m_real=realshop; } void SellBooks(){ Discount(); m_real->SellBooks(); Discount(); } void Discount(){ cout<<"11.11 discount"<<endl; } private: RealBookShop* m_real; }; void test12(){ RealBookShop* r=new RealBookShop; Taobao_proxy* p=new Taobao_proxy(r); p->SellBooks(); //http://blog.csdn.net/yangqiang387393/article/details/51395888 } class Request { public: int m_nNumber; }; class Manager { public: Manager(string temp) { name = temp; } void SetSuccessor(Manager* temp) { manager = temp; } virtual void GetRequest(Request* request) = 0; protected: Manager* manager; string name; }; class CommonManager : public Manager { public: CommonManager(string strTemp) : Manager(strTemp) {} virtual void GetRequest(Request* request) { if (request->m_nNumber>=0 && request->m_nNumber<1000) cout << name << " 處理了請求: " << request->m_nNumber << endl; else manager->GetRequest(request); } }; class Majordomo : public Manager { public: Majordomo(string strTemp) : Manager(strTemp) {} virtual void GetRequest(Request* request) { if (request->m_nNumber <= 5000) cout << name << " 處理了請求: " << request->m_nNumber << endl; else manager->GetRequest(request); } }; class GeneralManager: public Manager { public: GeneralManager(string name):Manager(name) {} virtual void GetRequest(Request* request) //總經理能夠處理全部請求 { cout << name << " 處理了請求: " << request->m_nNumber << endl; } }; void test13(){ Manager* common = new CommonManager("張經理"); Manager* major = new Majordomo("李總監"); GeneralManager* general = new GeneralManager("趙總"); common->SetSuccessor(major); major->SetSuccessor(general); Request* rq = new Request(); rq->m_nNumber = 999; common->GetRequest(rq); rq->m_nNumber = 4999; common->GetRequest(rq); rq->m_nNumber = 6999; common->GetRequest(rq); } /****************************************************************************/ class RoastCook { public: void MakeMutton() { cout << "烤羊肉" << endl; } void MakeChickenWing() { cout << "烤雞翅膀" << endl; } }; class Command { public: Command(RoastCook* temp) { receiver = temp; } virtual void ExecuteCmd() = 0; protected: RoastCook* receiver; }; class MakeMuttonCmd : public Command { public: MakeMuttonCmd(RoastCook* temp) : Command(temp) {} virtual void ExecuteCmd() { receiver->MakeMutton(); } }; class MakeChickenWingCmd : public Command { public: MakeChickenWingCmd(RoastCook* temp) : Command(temp) {} virtual void ExecuteCmd() { receiver->MakeChickenWing(); } }; class Waiter { public: void SetCmd(Command* temp){ m_commandList.push_back(temp); cout << "增長訂單" << endl; } void Notify(){ vector<Command*>::iterator it; for (it=m_commandList.begin(); it!=m_commandList.end(); ++it) (*it)->ExecuteCmd(); } protected: vector<Command*> m_commandList; }; void test14() { RoastCook* cook = new RoastCook(); Command* cmd1 = new MakeMuttonCmd(cook); Command* cmd2 = new MakeChickenWingCmd(cook); Waiter* girl = new Waiter(); girl->SetCmd(cmd1); girl->SetCmd(cmd2); girl->Notify(); } /****************************************************************************/ class Memento { private: string state; public: Memento(){} Memento(string s):state(s){}; string GetState(){return state;} }; class game { private: string state; public: void SetState(string state) { this->state=state;} Memento CreateMemento() { return Memento(state);} void SetMento(Memento mem) { this->state=mem.GetState(); } void Show() { cout<<"當前狀態爲:"<<state<<endl; } }; /* http://www.itnose.net/detail/6074926.html game --> Memento --<> CareTaker 玩家 備份存根 備份操做 */ class CareTaker { private: Memento memento; public: Memento GetMemento() { return memento; } void SetMemento(Memento men) { this->memento=men; cout<<"當前狀態信息已備份!"<<endl; } }; void test18() { game org; org.SetState("初始狀態"); org.Show(); CareTaker ct; ct.SetMemento(org.CreateMemento()); org.SetState("升級狀態!"); org.Show(); org.SetMento(ct.GetMemento()); org.Show(); } /****************************************************************************/ class Context { public: string input; string output; }; class AbstractExpression { public: virtual void Interpret(Context* context) = 0; }; class Expression : public AbstractExpression { public: virtual void Interpret(Context* context) { cout << "終端解釋器" << endl; } }; class NonTerminalExpression : public AbstractExpression { public: virtual void Interpret(Context* context) { cout << "非終端解釋器" << endl; } }; void test19( ) { Context* context = new Context(); vector<AbstractExpression*> express; express.push_back(new Expression()); express.push_back(new NonTerminalExpression()); express.push_back(new NonTerminalExpression()); vector<AbstractExpression*>::iterator it; for (it=express.begin(); it!=express.end(); ++it) { (*it)->Interpret(context); } } /****************************************************************************/ class Worker; class State{ public: virtual void doing(Worker* w){} }; class WorkingState: public State { public: void doing(Worker* worker); }; class SleepingState: public State { public: void doing(Worker* worker); }; class OtherState : public State { public: void doing(Worker* worker); }; class Worker { public: Worker() { state = new WorkingState(); } void setState(State* stat) { state = stat; } int getHour() { return hour;} void setHour(int x) { cout << "time is "<<x; hour = x; } void requestDoing() { state->doing(this); } private: State* state; int hour; }; void WorkingState::doing(Worker* worker) { if(worker->getHour() > 8 && worker->getHour() < 16) cout << ": WorkingState!" << endl; else { worker->setState(new OtherState()); worker->requestDoing(); } } void SleepingState::doing(Worker* worker) { if(worker->getHour() >= 21 || worker->getHour() < 5) cout << ": SleepingState!" << endl; else { worker->setState(new OtherState()); worker->requestDoing(); } } void OtherState::doing(Worker* worker) { if((worker->getHour() >= 5 && worker->getHour() < 8) || (worker->getHour() >= 16 && worker->getHour() < 21)) cout << "others!" << endl; else if(worker->getHour() >= 21 || worker->getHour() < 5) {worker->setState(new SleepingState()); worker->requestDoing();} else {worker->setState(new WorkingState()); worker->requestDoing();} } void test20() { Worker* pWorker = new Worker(); pWorker->setHour(12); pWorker->requestDoing(); pWorker->setHour(24); pWorker->requestDoing(); } /****************************************************************************/ class WeaponBehavior { public: void virtual useWeapon() = 0; }; class AK47:public WeaponBehavior { public: void useWeapon() { cout << "Use AK47 to shoot!" << endl; } }; class Knife:public WeaponBehavior { public: void useWeapon() { cout << "Use Knife to kill" << endl; } }; class Character { public: Character() { weapon = 0; } void setWeapon(WeaponBehavior *w) { this->weapon = w; } void virtual fight() = 0; protected: WeaponBehavior *weapon; }; class Killer:public Character { public: void fight() { if ( this->weapon == NULL) cout << "NO weapon! Please Set Weapon!" << endl; else weapon->useWeapon(); } }; void test21() { WeaponBehavior *ak47 = new AK47(); WeaponBehavior *knife = new Knife(); Character *kin = new Killer(); kin->fight(); kin->setWeapon(ak47); kin->fight(); kin->setWeapon(knife); kin->fight(); } /****************************************************************************/ template <typename T> class CaffeineBeverage { public: void PrepareRecipe() { cout << "燒水" << endl; static_cast<T *>(this)->Brew(); static_cast<T *>(this)->AddCondiments(); } }; class Coffee : public CaffeineBeverage<Coffee> { public: void Brew() { cout << "沖泡咖啡" << endl;} void AddCondiments() { cout << "加糖和牛奶" << endl;} }; class Tea : public CaffeineBeverage<Tea> { public: void Brew() { cout << "浸泡茶葉" << endl;} void AddCondiments() { cout << "加檸檬" << endl;} }; void test22() { Coffee c; c.PrepareRecipe(); //Tea t; t.PrepareRecipe(); } /****************************************************************************/ //http://www.tuicool.com/articles/BB3yQz class DrawAction { public: virtual void DrawLine() = 0; virtual void DrawPolygon() = 0; }; class DrawWithTexture : public DrawAction { public: void DrawLine() {cout << "繪製線"<< endl;} void DrawPolygon() {cout << "繪製多邊形"<< endl;} }; class DrawIn3DModel : public DrawAction { public: void DrawLine() {cout << "繪製3D模式下的線"<< endl;} void DrawPolygon() {cout << "繪製3D模式下的多邊形"<< endl;} }; class Element { public: virtual void Draw(DrawAction *visitor) = 0; }; class Line : public Element { public: void Draw(DrawAction *visitor) { visitor->DrawLine(); } }; class Polygon : public Element { public: void Draw(DrawAction *visitor) { visitor->DrawPolygon(); } }; void test23() { Element *pLine = new Line; //線 Element *pPoly = new Polygon;//形 DrawAction *p3DM = new DrawIn3DModel; pLine->Draw(p3DM); pPoly->Draw(p3DM); } /****************************************************************************/ int main() { cout<<"http://www.anycodes.cn/zh/"<<endl; return 0; }