├── .gitattributes ├── .gitignore ├── AbstractFactory └── AbstractFactory.cpp ├── Adapter └── Adapter.cpp ├── Bridge └── Bridge.cpp ├── Builder └── Builder.cpp ├── ChainOfResponsibility └── Chain.cpp ├── Command └── Command.cpp ├── Composite └── Composite.cpp ├── Decorator └── Decorator.cpp ├── Facade └── Facade.cpp ├── Factory └── Factory.cpp ├── Flyweight └── Flyweight.cpp ├── Interpreter └── Interpreter.cpp ├── Iterator └── Iterator.cpp ├── Mediator └── Mediator.cpp ├── Memento └── Memento.cpp ├── Observer ├── Observer.cpp ├── Observer.h └── testMove.cpp ├── Prototype └── Prototype.cpp ├── Proxy └── Proxy.cpp ├── README.md ├── SimpleFactory └── SimpleFactory.cpp ├── Singleton └── singleton.cpp ├── State └── State.cpp ├── Strategy └── Strategy.cpp ├── TemplateMethod └── Template.cpp └── Visitor └── Visitor.cpp /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Windows image file caches 2 | Thumbs.db 3 | ehthumbs.db 4 | 5 | # Folder config file 6 | Desktop.ini 7 | 8 | # Recycle Bin used on file shares 9 | $RECYCLE.BIN/ 10 | 11 | # Windows Installer files 12 | *.cab 13 | *.msi 14 | *.msm 15 | *.msp 16 | 17 | # Windows shortcuts 18 | *.lnk 19 | 20 | # ========================= 21 | # Operating System Files 22 | # ========================= 23 | 24 | # OSX 25 | # ========================= 26 | 27 | .DS_Store 28 | .AppleDouble 29 | .LSOverride 30 | 31 | # Thumbnails 32 | ._* 33 | 34 | # Files that might appear on external disk 35 | .Spotlight-V100 36 | .Trashes 37 | 38 | # Directories potentially created on remote AFP share 39 | .AppleDB 40 | .AppleDesktop 41 | Network Trash Folder 42 | Temporary Items 43 | .apdisk 44 | 45 | a.out 46 | *.json 47 | -------------------------------------------------------------------------------- /AbstractFactory/AbstractFactory.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | 6 | class User{ 7 | private: 8 | int _id; 9 | std::string _name; 10 | }; 11 | 12 | class UserOperation{ 13 | public: 14 | virtual void Insert(const User &user) = 0; 15 | virtual User GetUser(int id) = 0; 16 | }; 17 | 18 | class MongoUserOperation :public UserOperation{ 19 | public : 20 | void Insert(const User &user){ 21 | std::cout<<"MongoDB: insert user info"<(); 67 | }else if(type == MP4){ 68 | advancedMusicPlayer = std::make_shared(); 69 | } 70 | 71 | } 72 | void play(AudioType type,const std::string &filename) override{ 73 | if(type == VLC){ 74 | advancedMusicPlayer->playVLC(filename); 75 | }else if(type == MP4){ 76 | advancedMusicPlayer->playMP4(filename); 77 | } 78 | } 79 | private: 80 | std::shared_ptr advancedMusicPlayer; 81 | }; 82 | 83 | class AudioPlayer : public MediaPlayer{ 84 | private: 85 | std::shared_ptr mediaAdapter; 86 | public: 87 | 88 | void play(AudioType type,const std::string &fileName) override{ 89 | if(type == MP3){ 90 | std::cout<<"player mp3 file. Name: "<(type); 93 | mediaAdapter->play(type,fileName); 94 | }else{ 95 | std::cout<<"Invalid media. "< player = std::make_shared(); 103 | player->play(MP3,"test1.mp3"); 104 | player->play(MP4,"test2.mp4"); 105 | player->play(VLC,"test3.vlc"); 106 | return 0; 107 | } -------------------------------------------------------------------------------- /Bridge/Bridge.cpp: -------------------------------------------------------------------------------- 1 | //g++ Bridge.cpp -Wc++11-extensions -std=c++11 2 | 3 | #include 4 | #include 5 | class DrawAPI{ 6 | public: 7 | virtual void drawCircle(int radius,int x,int y) = 0; 8 | }; 9 | 10 | class RedCircle:public DrawAPI{ 11 | public: 12 | void drawCircle(int radius,int x,int y){ 13 | std::cout<<"Drawing Circle[ color: red, radius: "< _drawAPI; 28 | Shape(const std::shared_ptr &drawapi){ 29 | _drawAPI = drawapi; 30 | } 31 | public: 32 | virtual void draw() = 0; 33 | }; 34 | 35 | 36 | class Circle:public Shape{ 37 | private: 38 | int _x, _y, _radius; 39 | 40 | public: 41 | Circle(int x, int y, int radius, const std::shared_ptr &drawapi):Shape(drawapi) { 42 | _x = x; 43 | _y = y; 44 | _radius = radius; 45 | } 46 | 47 | void draw(){ 48 | _drawAPI->drawCircle(_radius,_x,_y); 49 | } 50 | }; 51 | 52 | int main(){ 53 | std::shared_ptr redcircle = std::make_shared(100,100,10,std::make_shared()); 54 | 55 | redcircle->draw(); 56 | 57 | return 0; 58 | 59 | } -------------------------------------------------------------------------------- /Builder/Builder.cpp: -------------------------------------------------------------------------------- 1 | //g++ Builder.cpp -Wc++11-extensions -std=c++11 2 | #include 3 | #include 4 | #include 5 | 6 | class Packing{ 7 | public: 8 | virtual std::string pack() = 0; 9 | }; 10 | 11 | class Item{ 12 | public: 13 | virtual std::string name() = 0; 14 | virtual std::shared_ptr packing() = 0; 15 | virtual float price() = 0; 16 | }; 17 | 18 | 19 | class Wrapper : public Packing{ 20 | public: 21 | std::string pack() override{ 22 | return "Wrapper"; 23 | } 24 | }; 25 | 26 | class Bottle : public Packing{ 27 | public: 28 | std::string pack() override{ 29 | return "Bottle"; 30 | } 31 | }; 32 | 33 | class Burger : public Item{ 34 | public: 35 | std::shared_ptr packing() override{ 36 | return std::make_shared(); 37 | } 38 | }; 39 | 40 | class ColdDrink:public Item{ 41 | std::shared_ptr packing() override{ 42 | return std::make_shared(); 43 | } 44 | }; 45 | 46 | 47 | class VegBurger : public Burger{ 48 | public: 49 | float price() override{ 50 | return 25.0; 51 | } 52 | std::string name() override{ 53 | return "Veg BUrger"; 54 | } 55 | 56 | }; 57 | 58 | class ChickenBurger : public Burger{ 59 | public: 60 | float price() override{ 61 | return 50.0; 62 | } 63 | std::string name() override{ 64 | return "Chicken BUrger"; 65 | } 66 | 67 | }; 68 | 69 | class Coke : public ColdDrink{ 70 | public: 71 | float price() override{ 72 | return 30.0f; 73 | } 74 | std::string name() override{ 75 | return "Coke"; 76 | } 77 | }; 78 | 79 | class Pepsi : public ColdDrink{ 80 | public: 81 | float price() override{ 82 | return 31.0f; 83 | } 84 | std::string name() override{ 85 | return "Pepsi"; 86 | } 87 | }; 88 | 89 | class Meal{ 90 | public: 91 | std::vector > _items; 92 | 93 | void addItem(const std::shared_ptr &item){ 94 | _items.push_back(item); 95 | } 96 | 97 | float getTotalCost(){ 98 | float cost = 0.0; 99 | for(auto v:_items){ 100 | cost += v->price(); 101 | } 102 | return cost; 103 | } 104 | 105 | void showItems(){ 106 | for(auto v: _items){ 107 | std::cout<<"Item :"<name(); 108 | std::cout<<", Packing :"<packing()->pack(); 109 | std::cout<<", Price :"<price()<()); 123 | meal.addItem(std::make_shared()); 124 | return meal; 125 | } 126 | }; 127 | 128 | int main(){ 129 | 130 | MealBuilder builder; 131 | Meal meal = builder.prepareVegMeal(); 132 | meal.showItems(); 133 | 134 | 135 | return 0; 136 | } -------------------------------------------------------------------------------- /ChainOfResponsibility/Chain.cpp: -------------------------------------------------------------------------------- 1 | //compile using g++ Chain.cpp -Wc++11-extensions -std=c++11 2 | #include 3 | #include 4 | #include 5 | 6 | class AbstractLogger{ 7 | public: 8 | const static int INFO = 1; 9 | const static int DEBUG = 2; 10 | const static int ERROR = 3; 11 | void logMessage(int level,const std::string &message){ 12 | if(this->level <= level){ 13 | write(message); 14 | } 15 | if(nextLogger != nullptr){ 16 | nextLogger->logMessage(level,message); 17 | } 18 | } 19 | 20 | void setNextLogger(std::shared_ptr nextLogger){ 21 | this->nextLogger = nextLogger; 22 | } 23 | 24 | protected: 25 | int level; 26 | std::shared_ptr nextLogger; 27 | virtual void write(const std::string &message) = 0; 28 | 29 | }; 30 | 31 | const int AbstractLogger::INFO; 32 | const int AbstractLogger::DEBUG; 33 | const int AbstractLogger::ERROR; 34 | 35 | class ConsoleLogger:public AbstractLogger { 36 | 37 | public: 38 | ConsoleLogger(int level){ 39 | this->level = level; 40 | } 41 | 42 | protected: 43 | void write(const std::string &message) override { 44 | std::cout<<"Standard Console::Logger: "<level = level; 53 | } 54 | 55 | protected: 56 | void write(const std::string &message) override { 57 | std::cout<<"Error Console::Logger: "<level = level; 66 | } 67 | 68 | protected: 69 | void write(const std::string &message) override { 70 | std::cout<<"File::Logger: "< getChainOfLoggers(){ 75 | 76 | std::shared_ptr errorLogger = std::make_shared(ConsoleLogger::ERROR); 77 | std::shared_ptr fileLogger = std::make_shared(ConsoleLogger::DEBUG); 78 | std::shared_ptr consoleLogger = std::make_shared(ConsoleLogger::INFO); 79 | 80 | errorLogger->setNextLogger(fileLogger); 81 | fileLogger->setNextLogger(consoleLogger); 82 | return errorLogger; 83 | } 84 | 85 | 86 | int main(){ 87 | 88 | 89 | 90 | 91 | std::shared_ptr loggerChain = getChainOfLoggers(); 92 | 93 | loggerChain->logMessage(AbstractLogger::INFO, 94 | "This is an information."); 95 | 96 | loggerChain->logMessage(AbstractLogger::DEBUG, 97 | "This is an debug level information."); 98 | 99 | loggerChain->logMessage(AbstractLogger::ERROR, 100 | "This is an error information."); 101 | 102 | return 0; 103 | } -------------------------------------------------------------------------------- /Command/Command.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Receiver{ 7 | public: 8 | static void CookRice(){ 9 | cout<<"炒米饭"< > _orders; 48 | void SetOrder(const shared_ptr command){ 49 | _orders.push_back(command); 50 | } 51 | 52 | void Notify(){ 53 | for(auto o:_orders){ 54 | o->Execute(); 55 | } 56 | } 57 | }; 58 | 59 | int main(){ 60 | 61 | Receiver receiver; 62 | // Command *rice =new CookRiceCommand(receiver); 63 | // Command *noodles = new CookNoodlesCommand(receiver); 64 | 65 | shared_ptr rice = make_shared(receiver); 66 | shared_ptr noodles = make_shared(receiver); 67 | 68 | Waiter waiter ; 69 | waiter.SetOrder(rice); 70 | waiter.SetOrder(move(noodles)); 71 | 72 | waiter.Notify(); 73 | return 0; 74 | } 75 | 76 | -------------------------------------------------------------------------------- /Composite/Composite.cpp: -------------------------------------------------------------------------------- 1 | //compile using g++ Composite.cpp -Wc++11-extensions -std=c++11 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | class Company{ 8 | public: 9 | std::string _name; 10 | Company(const std::string &name){ 11 | _name = name; 12 | } 13 | virtual void Add(const std::shared_ptr &c) = 0; 14 | virtual void Remove(const std::shared_ptr &c) = 0; 15 | virtual void Display(int depth) = 0; 16 | virtual void LineOfDuty() = 0; 17 | }; 18 | 19 | class ConcreteCompany:public Company{ 20 | public: 21 | ConcreteCompany(const std::string &name):Company(name){ 22 | 23 | } 24 | void Add(const std::shared_ptr &c) override{ 25 | 26 | _children.insert(c); 27 | } 28 | void Remove(const std::shared_ptr &c) override{ 29 | 30 | _children.erase(c); 31 | } 32 | void Display(int depth) override{ 33 | 34 | std::cout<Display(depth+2); 37 | } 38 | } 39 | void LineOfDuty() override{ 40 | 41 | for(auto c : _children){ 42 | c->LineOfDuty(); 43 | } 44 | } 45 | private: 46 | std::set > _children; 47 | }; 48 | 49 | class HRDepartment:public Company{ 50 | public: 51 | HRDepartment(const std::string &name):Company(name){ 52 | 53 | } 54 | void Add(const std::shared_ptr &c) override{ 55 | 56 | } 57 | void Remove(const std::shared_ptr &c) override{ 58 | 59 | } 60 | void Display(int depth) override{ 61 | std::cout< &c) override{ 74 | 75 | } 76 | void Remove(const std::shared_ptr &c) override{ 77 | 78 | } 79 | void Display(int depth) override{ 80 | std::cout< root = std::make_shared("北京总公司"); 89 | root->Add(std::make_shared("总公司人力资源总部")); 90 | root->Add(std::make_shared("总公司研发总部")); 91 | 92 | std::shared_ptr comp1 = std::make_shared("河北总公司"); 93 | comp1->Add(std::make_shared("河北分公司人力资源部")); 94 | comp1->Add(std::make_shared("河北分公司研发部")); 95 | 96 | root->Add(comp1); 97 | 98 | root->Display(1); 99 | 100 | root->LineOfDuty(); 101 | 102 | return 0; 103 | } -------------------------------------------------------------------------------- /Decorator/Decorator.cpp: -------------------------------------------------------------------------------- 1 | //g++ Decorator.cpp -Wc++11-extensions -std=c++11 2 | #include 3 | #include 4 | #include 5 | 6 | class Person{ 7 | public: 8 | std::string _name; 9 | Person(){} 10 | Person(std::string &&name){ 11 | //std::cout<<"call move Person"<_name = std::move(component._name); 16 | } 17 | // Person& operator= (Person &&component){ 18 | // std::cout<<"call move operator ="<_name = std::move(component._name); 20 | // return *this; 21 | // } 22 | virtual void Show(){ 23 | std::cout<<"decorate for "<<_name< &person){ 33 | this->_person = person; 34 | } 35 | void Show(){ 36 | _person->Show(); 37 | } 38 | 39 | private: 40 | std::shared_ptr _person; 41 | 42 | }; 43 | 44 | class TShirts:public Finery{ 45 | public: 46 | TShirts(){} 47 | void Show(){ 48 | std::cout<<"T Shirts "; 49 | Finery::Show(); 50 | } 51 | }; 52 | 53 | class BigTrouser:public Finery{ 54 | 55 | public: 56 | BigTrouser(){} 57 | void Show(){ 58 | std::cout<<"Big Trousers "; 59 | Finery::Show(); 60 | } 61 | }; 62 | 63 | int main(){ 64 | 65 | std::string name("Simon"); 66 | std::shared_ptr xc = std::make_shared(std::move(name)); 67 | 68 | std::shared_ptr bt = std::make_shared(); 69 | std::shared_ptr ts = std::make_shared(); 70 | 71 | 72 | ts->Decorate(xc); 73 | bt->Decorate(ts); 74 | 75 | bt->Show(); 76 | 77 | return 0; 78 | } -------------------------------------------------------------------------------- /Facade/Facade.cpp: -------------------------------------------------------------------------------- 1 | //g++ Facade.cpp -Wc++11-extensions -std=c++11 2 | #include 3 | #include 4 | 5 | class Shape{ 6 | public: 7 | virtual void draw() = 0; 8 | }; 9 | 10 | class Rectangle : public Shape{ 11 | public: 12 | void draw() override { 13 | std::cout<<"draw Rectangle."< _rectangle; 35 | std::shared_ptr _square; 36 | std::shared_ptr _circle; 37 | 38 | public: 39 | ShapeMaker(){ 40 | _rectangle = std::make_shared(); 41 | _square = std::make_shared(); 42 | _circle = std::make_shared(); 43 | } 44 | 45 | void drawCircle(){ 46 | _circle->draw(); 47 | } 48 | void drawSquare(){ 49 | _square->draw(); 50 | } 51 | void drawRectangle(){ 52 | _rectangle->draw(); 53 | } 54 | 55 | }; 56 | 57 | 58 | int main(){ 59 | 60 | std::shared_ptr shapemaker(new ShapeMaker()); 61 | shapemaker->drawCircle(); 62 | shapemaker->drawRectangle(); 63 | shapemaker->drawSquare(); 64 | 65 | return 0; 66 | } -------------------------------------------------------------------------------- /Factory/Factory.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | class ArithmeticOperation{ 6 | 7 | public: 8 | 9 | ArithmeticOperation(){ 10 | _numberA = 0; 11 | _numberB = 0; 12 | } 13 | virtual double GetResult() = 0; 14 | 15 | void SetNumberA(double a){ 16 | _numberA =a; 17 | } 18 | void SetNumberB(double b){ 19 | _numberB =b; 20 | } 21 | 22 | protected: 23 | 24 | double _numberA; 25 | double _numberB; 26 | 27 | 28 | }; 29 | 30 | class Add:public ArithmeticOperation{ 31 | public: 32 | double GetResult(){ 33 | return _numberA + _numberB; 34 | } 35 | }; 36 | 37 | class Sub:public ArithmeticOperation{ 38 | public: 39 | double GetResult(){ 40 | return _numberA - _numberB; 41 | } 42 | }; 43 | 44 | class Mul:public ArithmeticOperation{ 45 | public: 46 | double GetResult(){ 47 | return _numberA * _numberB; 48 | } 49 | }; 50 | 51 | class Del:public ArithmeticOperation{ 52 | public: 53 | double GetResult(){ 54 | 55 | if(_numberB == 0){ 56 | throw(std::string("Dividend cannot be zero.")); 57 | } 58 | return _numberA / _numberB; 59 | } 60 | }; 61 | 62 | class IFactory { 63 | public: 64 | virtual std::shared_ptr createArithmeticOperation() = 0; 65 | }; 66 | 67 | class AddFactory:public IFactory{ 68 | public: 69 | std::shared_ptr createArithmeticOperation(){ 70 | return std::make_shared(); 71 | } 72 | }; 73 | class SubFactory:public IFactory{ 74 | public: 75 | std::shared_ptr createArithmeticOperation(){ 76 | return std::make_shared(); 77 | } 78 | }; 79 | class MulFactory:public IFactory{ 80 | public: 81 | std::shared_ptr createArithmeticOperation(){ 82 | return std::make_shared(); 83 | } 84 | }; 85 | class DelFactory:public IFactory{ 86 | public: 87 | std::shared_ptr createArithmeticOperation(){ 88 | return std::make_shared(); 89 | } 90 | }; 91 | 92 | int main(){ 93 | 94 | std::shared_ptr addfactory= std::make_shared(); 95 | std::shared_ptr add = addfactory->createArithmeticOperation(); 96 | add->SetNumberA(2); 97 | add->SetNumberB(3); 98 | 99 | std::cout<<"The add result is:"<GetResult()< 3 | #include 4 | #include 5 | #include 6 | #include 7 | class Shape{ 8 | 9 | public: 10 | virtual void draw() = 0; 11 | }; 12 | 13 | class Circle: public Shape{ 14 | 15 | public: 16 | Circle(const std::string &color){ 17 | this->color = color; 18 | } 19 | 20 | void setX(int x) { 21 | this->x = x; 22 | } 23 | 24 | void setY(int y) { 25 | this->y = y; 26 | } 27 | 28 | void setRadius(int radius) { 29 | this->radius = radius; 30 | } 31 | 32 | void draw() override { 33 | std::cout<<"Circle: Draw() [Color : "< > circleMap; 45 | 46 | public: 47 | static std::shared_ptr getCircle(const std::string &color) { 48 | 49 | if(circleMap.count(color) == 0) { 50 | std::shared_ptr shape = std::make_shared(color); 51 | circleMap.insert(std::pair >(color,shape)); 52 | std::cout<<"Creating circle of color : "< > ShapeFactory::circleMap; 65 | 66 | int main() 67 | { 68 | std::vector colors; 69 | colors.push_back("Red"); 70 | colors.push_back("Green"); 71 | colors.push_back("Blue"); 72 | colors.push_back("White"); 73 | colors.push_back("Black"); 74 | 75 | for(int i=0; i < 20; ++i) { 76 | std::shared_ptr circle = 77 | ShapeFactory::getCircle(colors[i%5]); 78 | circle->setX(i); 79 | circle->setY(i+3); 80 | circle->setRadius(100); 81 | circle->draw(); 82 | //print(); 83 | std::cout<<"-------"< 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | //using unique_ptr this example is not necessary,but only for being familar with grammar 9 | class Expression{ 10 | public: 11 | virtual bool interpret(const std::string &context) = 0; 12 | virtual ~Expression(){} 13 | 14 | }; 15 | 16 | class TerminalExpression:public Expression { 17 | 18 | private: 19 | std::string data; 20 | 21 | public: 22 | TerminalExpression(const std::string &data){ 23 | this->data = data; 24 | } 25 | 26 | bool interpret(const std::string &context) override{ 27 | if(context.find(data) != std::string::npos){ 28 | return true; 29 | } 30 | return false; 31 | } 32 | }; 33 | 34 | class OrExpression:public Expression { 35 | private: 36 | std::unique_ptr expr1; 37 | std::unique_ptr expr2; 38 | 39 | public: 40 | OrExpression( std::unique_ptr &expr1, std::unique_ptr &expr2) { 41 | this->expr1 = std::move(expr1); 42 | this->expr2 = std::move(expr2); 43 | } 44 | bool interpret(const std::string &context) { 45 | return expr1->interpret(context) || expr2->interpret(context); 46 | } 47 | }; 48 | 49 | class AndExpression: public Expression { 50 | 51 | private: 52 | std::unique_ptr expr1; 53 | std::unique_ptr expr2; 54 | 55 | public: 56 | AndExpression( std::unique_ptr &expr1, std::unique_ptr &expr2) { 57 | this->expr1 = std::move(expr1); 58 | this->expr2 = std::move(expr2); 59 | } 60 | bool interpret(const std::string &context) override { 61 | return expr1->interpret(context) && expr2->interpret(context); 62 | } 63 | }; 64 | 65 | int main(){ 66 | std::unique_ptr robert(new TerminalExpression("Robert")); 67 | std::unique_ptr john(new TerminalExpression("John")); 68 | std::unique_ptr isMale(new OrExpression(robert, john)); 69 | 70 | std::unique_ptr julie(new TerminalExpression("Julie")); 71 | std::unique_ptr married(new TerminalExpression("Married")); 72 | std::unique_ptr isMarriedWoman(new AndExpression(julie, married)); 73 | 74 | std::cout<<"John is Male? "<interpret("John")<interpret("Married Julie")< 4 | #include 5 | #include 6 | #include 7 | template 8 | class Iterator{ 9 | public: 10 | virtual bool hasNext() = 0; 11 | virtual T& next() = 0; 12 | 13 | }; 14 | 15 | template 16 | class Container{ 17 | public: 18 | virtual Iterator* getIterator() = 0; 19 | virtual void add(const T &data) = 0; 20 | virtual T& get(int idx) = 0; 21 | virtual int count() = 0; 22 | }; 23 | 24 | template 25 | class NameRepository; 26 | 27 | template 28 | class NameIterator : public Iterator{ 29 | 30 | public: 31 | NameIterator(Container *namerepository){ 32 | _namerepository = namerepository; 33 | _index = 0; 34 | } 35 | bool hasNext() override{ 36 | return _index < _namerepository->count(); 37 | } 38 | T& next() override{ 39 | if(hasNext()){ 40 | return _namerepository->get(_index++); 41 | } 42 | return _end; 43 | } 44 | 45 | private: 46 | Container *_namerepository; 47 | int _index; 48 | static T _end; 49 | }; 50 | 51 | template 52 | T NameIterator::_end; 53 | 54 | template 55 | class NameRepository:public Container { 56 | public: 57 | NameRepository(){} 58 | 59 | Iterator* getIterator() override{ 60 | return new NameIterator(this); 61 | } 62 | void add(const T &data) override{ 63 | _data.push_back(data); 64 | } 65 | T& get(int idx) override{ 66 | return _data[idx]; 67 | } 68 | int count() override{ 69 | return _data.size(); 70 | } 71 | private: 72 | std::vector _data; 73 | }; 74 | 75 | 76 | 77 | int main(){ 78 | 79 | std::shared_ptr > name = std::make_shared >(); 80 | 81 | name->add("one"); 82 | name->add("two"); 83 | name->add("three"); 84 | 85 | std::cout<<"Count:"<count()< *iterator = name->getIterator(); 87 | 88 | //std::shared_ptr > iterator = name->getIterator(); 89 | 90 | 91 | // std::cout<<"Count:"<count()<hasNext()){ 93 | std::cout<next()< 4 | #include 5 | #include 6 | class User; 7 | class ChatRoom { 8 | public: 9 | static void showMessage(User *user, const std::string &message); 10 | }; 11 | 12 | class User { 13 | private: 14 | std::string name; 15 | public : 16 | std::string getName() { 17 | return name; 18 | } 19 | 20 | void setName(const std::string &name) { 21 | this->name = name; 22 | } 23 | 24 | User(const std::string &name){ 25 | this->name = name; 26 | } 27 | 28 | void sendMessage(const std::string &message){ 29 | ChatRoom::showMessage(this,message); 30 | } 31 | }; 32 | 33 | void ChatRoom::showMessage(User *user, const std::string &message){ 34 | std::cout<<" ["<getName()<<"] : "< 3 | #include 4 | #include 5 | #include 6 | 7 | class Memento{ 8 | public: 9 | Memento(const std::string &state){ 10 | _state = state; 11 | } 12 | 13 | std::string getState(){ 14 | return _state; 15 | } 16 | 17 | private: 18 | std::string _state; 19 | 20 | }; 21 | 22 | class Originator{ 23 | public: 24 | void setState(const std::string &state){ 25 | _state = state; 26 | } 27 | 28 | std::string getState(){ 29 | return _state; 30 | } 31 | 32 | std::shared_ptr saveStateToMemento(){ 33 | return std::make_shared(_state); 34 | } 35 | 36 | void getStateFromMemento(const std::shared_ptr &memento){ 37 | _state = memento->getState(); 38 | } 39 | private: 40 | std::string _state; 41 | }; 42 | 43 | class CareTaker{ 44 | public: 45 | void add (const std::shared_ptr &state){ 46 | _mementos.push_back(state); 47 | } 48 | std::shared_ptr get(int idx){ 49 | return _mementos[idx]; 50 | } 51 | private: 52 | std::vector > _mementos; 53 | }; 54 | 55 | 56 | int main(){ 57 | 58 | std::shared_ptr originator = std::make_shared(); 59 | std::shared_ptr caretaker = std::make_shared(); 60 | 61 | originator->setState("State #1"); 62 | originator->setState("State #2"); 63 | caretaker->add(originator->saveStateToMemento()); 64 | originator->setState("State #3"); 65 | caretaker->add(originator->saveStateToMemento()); 66 | 67 | originator->setState("State #4"); 68 | std::cout<<"Current State: "<getState()<getStateFromMemento(caretaker->get(0)); 70 | std::cout<<"First saved State: "<getState()<getStateFromMemento(caretaker->get(1)); 72 | std::cout<<"Second saved State: "<getState()< &sub){ 4 | _name = name; 5 | _sub = sub; 6 | } 7 | 8 | Farmer::Farmer(const std::string &name,const std::shared_ptr &sub):Observer(name,sub){ 9 | 10 | } 11 | void Farmer::Update(){ 12 | std::cout<<_name<<":"<<_sub->getSubjectState()< &sub):Observer(name,sub){ 16 | 17 | } 18 | void Worker::Update(){ 19 | std::cout<<_name<<":"<<_sub->getSubjectState()< &obs){ 30 | _observers.insert(obs); 31 | } 32 | void Wind::Detach(const std::shared_ptr &obs){ 33 | _observers.erase(obs); 34 | } 35 | void Wind::Notify() 36 | { 37 | for(auto v: _observers){ 38 | v->Update(); 39 | } 40 | } 41 | 42 | void Rain::Attach(const std::shared_ptr &obs){ 43 | _observers.insert(obs); 44 | } 45 | void Rain::Detach(const std::shared_ptr &obs){ 46 | _observers.erase(obs); 47 | } 48 | void Rain::Notify() 49 | { 50 | for(auto v: _observers){ 51 | v->Update(); 52 | } 53 | } 54 | 55 | int main(){ 56 | 57 | std::shared_ptr sub = std::make_shared(); 58 | 59 | std::shared_ptr farmer = std::make_shared("farmer",sub); 60 | std::shared_ptr worker = std::make_shared("worker",sub); 61 | 62 | sub->Attach(farmer); 63 | sub->Attach(worker); 64 | 65 | sub->setSubjectState("The wind is coming!!!!!"); 66 | 67 | sub->Notify(); 68 | 69 | 70 | 71 | return 0; 72 | } -------------------------------------------------------------------------------- /Observer/Observer.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | class Subject; 7 | class Observer{ 8 | public: 9 | virtual void Update() = 0; 10 | Observer(const std::string name,const std::shared_ptr &sub); 11 | protected: 12 | std::shared_ptr _sub; 13 | std::string _name; 14 | }; 15 | class Farmer : public Observer{ 16 | public: 17 | Farmer(const std::string &name,const std::shared_ptr &sub); 18 | void Update(); 19 | }; 20 | class Worker : public Observer{ 21 | public: 22 | Worker(const std::string &name,const std::shared_ptr &sub); 23 | void Update(); 24 | }; 25 | 26 | 27 | 28 | //weather report subject 29 | class Subject{ 30 | public: 31 | void setSubjectState(std::string &&str); 32 | std::string getSubjectState(); 33 | 34 | virtual void Attach(const std::shared_ptr &obs) = 0; 35 | virtual void Detach(const std::shared_ptr &obs) = 0; 36 | virtual void Notify() = 0; 37 | 38 | private: 39 | std::string subjectState; 40 | }; 41 | class Wind: public Subject{ 42 | 43 | public: 44 | 45 | void Attach(const std::shared_ptr &obs); 46 | void Detach(const std::shared_ptr &obs); 47 | void Notify(); 48 | 49 | private: 50 | std::set > _observers; 51 | }; 52 | 53 | class Rain: public Subject{ 54 | 55 | public: 56 | 57 | void Attach(const std::shared_ptr &obs); 58 | void Detach(const std::shared_ptr &obs); 59 | void Notify(); 60 | 61 | private: 62 | std::set > _observers; 63 | }; 64 | 65 | -------------------------------------------------------------------------------- /Observer/testMove.cpp: -------------------------------------------------------------------------------- 1 | 2 | //compile using g++ testMove.cpp -Wc++11-extensions -std=c++11 3 | #include 4 | using namespace std; 5 | 6 | class Widget{ 7 | 8 | }; 9 | 10 | void process(const Widget &lval){ 11 | cout<<"left value"< 19 | void logAndProcess(T&& param){ 20 | process(std::forward(param)); 21 | } 22 | 23 | 24 | int main(){ 25 | Widget w; 26 | logAndProcess(w); 27 | logAndProcess(std::move(w)); 28 | return 0; 29 | } -------------------------------------------------------------------------------- /Prototype/Prototype.cpp: -------------------------------------------------------------------------------- 1 | //https://codereview.stackexchange.com/questions/65284/polymorphic-template-cloning-class 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | template 8 | class ICloneable{ 9 | public: 10 | virtual std::shared_ptr clone() const = 0; 11 | }; 12 | 13 | 14 | class WorkExperience{ 15 | public: 16 | WorkExperience(){} 17 | WorkExperience(std::string &&date,std::string company){ 18 | std::cout<<"constructor"<_company = work._company; 26 | this->_workDate = work._workDate; 27 | } 28 | WorkExperience& operator = (const WorkExperience &work){ 29 | std::cout<<"operator = "<{ 49 | private: 50 | std::string _name; 51 | std::string _sex; 52 | std::string _age; 53 | std::shared_ptr _work; 54 | public: 55 | 56 | Resume(){ 57 | _work = std::make_shared(); 58 | 59 | } 60 | 61 | Resume(std::string &name,std::string &sex,std::string &age,std::string &date,std::string &company){ 62 | 63 | _name = std::move(name); 64 | _sex = std::move(sex); 65 | _age = std::move(age); 66 | _work = std::make_shared(std::move(date),std::move(company)); 67 | } 68 | 69 | void setCompany(const std::string &company){ 70 | _work->setCompany(company); 71 | } 72 | 73 | void setWorkDate(const std::string &date){ 74 | _work->setWorkDate(date); 75 | } 76 | 77 | std::shared_ptr clone() const{ 78 | 79 | std::shared_ptr rv = std::make_shared(); 80 | 81 | rv->_name = this->_name; 82 | rv->_age = this->_age; 83 | rv->_sex = this->_sex; 84 | 85 | 86 | rv->setCompany(this->_work->_company); 87 | rv->setWorkDate(this->_work->_workDate); 88 | 89 | //*(rv->_work) = *(this->_work); 90 | 91 | return rv; 92 | } 93 | 94 | void PrintResume(){ 95 | std::cout<<"Name: "<<_name<_company<_workDate< resume2 = resume.clone(); 119 | 120 | resume2->PrintResume(); 121 | 122 | resume2->setWorkDate("2013-2019"); 123 | 124 | resume.PrintResume(); 125 | resume2->PrintResume(); 126 | 127 | return 0; 128 | 129 | //std:: 130 | 131 | } -------------------------------------------------------------------------------- /Proxy/Proxy.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | //compile using g++ Proxy.cpp -Wc++11-extensions -std=c++11 6 | class NetworkOperator{ 7 | public: 8 | virtual void Login(const std::string &url) = 0; 9 | virtual void DownloadResources(const std::string &url) = 0; 10 | }; 11 | 12 | class ChinaUnicom: public NetworkOperator{ 13 | 14 | public: 15 | std::string _name; 16 | ChinaUnicom(){ 17 | //std::cout<<"Call default constructor"< 2 | #include 3 | #include 4 | 5 | class ArithmeticOperation{ 6 | 7 | public: 8 | 9 | ArithmeticOperation(){ 10 | _numberA = 0; 11 | _numberB = 0; 12 | } 13 | virtual double GetResult()=0; 14 | 15 | void SetNumberA(double a){ 16 | _numberA =a; 17 | } 18 | void SetNumberB(double b){ 19 | _numberB =b; 20 | } 21 | 22 | protected: 23 | 24 | double _numberA; 25 | double _numberB; 26 | 27 | 28 | }; 29 | 30 | class Add:public ArithmeticOperation{ 31 | public: 32 | double GetResult(){ 33 | return _numberA + _numberB; 34 | } 35 | }; 36 | 37 | class Sub:public ArithmeticOperation{ 38 | public: 39 | double GetResult(){ 40 | return _numberA - _numberB; 41 | } 42 | }; 43 | 44 | class Mul:public ArithmeticOperation{ 45 | public: 46 | double GetResult(){ 47 | return _numberA * _numberB; 48 | } 49 | }; 50 | 51 | class Del:public ArithmeticOperation{ 52 | public: 53 | double GetResult(){ 54 | 55 | if(_numberB == 0){ 56 | throw(std::string("Dividend cannot be zero.")); 57 | } 58 | return _numberA / _numberB; 59 | } 60 | }; 61 | 62 | class OperationFactory { 63 | 64 | public: 65 | 66 | static std::shared_ptr createArithmeticOperation(char operation){ 67 | 68 | switch (operation) 69 | { 70 | case '+': 71 | return std::make_shared(); 72 | break; 73 | case '-': 74 | return std::make_shared(); 75 | break; 76 | case '*': 77 | return std::make_shared(); 78 | break; 79 | case '/': 80 | return std::make_shared(); 81 | break; 82 | default: 83 | return nullptr; 84 | break; 85 | } 86 | } 87 | }; 88 | 89 | int main(){ 90 | std::shared_ptr add = OperationFactory::createArithmeticOperation('+'); 91 | if(add ==nullptr){ 92 | std::cout<<"operation is invalid."<SetNumberA(4); 96 | add->SetNumberB(5); 97 | std::cout<<"The add result is: "<GetResult()< del = OperationFactory::createArithmeticOperation('/'); 101 | if(del ==nullptr){ 102 | std::cout<<"operation is invalid."<SetNumberA(4); 106 | del->SetNumberB(0); 107 | std::cout<<"The add result is: "<GetResult()< 3 | #include 4 | #include 5 | 6 | template 7 | class Singleton{ 8 | 9 | public: 10 | static T* GetInstance(){ 11 | 12 | if(_instance == nullptr){ 13 | _lock->lock(); 14 | if(_instance == nullptr){ 15 | _instance = new T(); 16 | } 17 | _lock->unlock(); 18 | } 19 | return _instance; 20 | } 21 | 22 | private: 23 | Singleton(){} 24 | Singleton(const Singleton&); 25 | Singleton& operator=(const Singleton&); 26 | static T *_instance;//非const 的static 成员必须在列外进行初始化 27 | static std::mutex *_lock; 28 | }; 29 | 30 | template 31 | T* Singleton::_instance = nullptr; 32 | 33 | template 34 | std::mutex* Singleton::_lock = new std::mutex(); 35 | 36 | template 37 | class Singleton11{ 38 | public: 39 | static std::unique_ptr GetInstance(){ 40 | 41 | return _instance; 42 | 43 | } 44 | private: 45 | Singleton11(){ 46 | 47 | } 48 | static std::unique_ptr _instance; 49 | }; 50 | 51 | template 52 | std::unique_ptr Singleton11::_instance = std::unique_ptr(new T()); 53 | 54 | 55 | 56 | 57 | template 58 | class Singlenton_ehan{ 59 | 60 | public: 61 | static T& GetInstance(){ 62 | return _instance; 63 | } 64 | private: 65 | Singlenton_ehan(){} 66 | static T _instance; 67 | }; 68 | 69 | template 70 | T Singlenton_ehan::_instance; 71 | 72 | 73 | class TestSingleton{ 74 | public: 75 | void PrintMyself(){ 76 | std::cout<(this)<::GetInstance(); 83 | std::cout<(instance)<PrintMyself(); 85 | 86 | TestSingleton *instance2 = Singleton::GetInstance(); 87 | instance2->PrintMyself(); 88 | 89 | TestSingleton &instance3 = Singlenton_ehan::GetInstance(); 90 | instance3.PrintMyself(); 91 | 92 | TestSingleton &instance4 = Singlenton_ehan::GetInstance(); 93 | instance4.PrintMyself(); 94 | 95 | auto instance5 = Singleton11::GetInstance(); 96 | instance5->PrintMyself(); 97 | 98 | auto instance6 = Singleton11::GetInstance(); 99 | instance6->PrintMyself(); 100 | 101 | return 0; 102 | 103 | } -------------------------------------------------------------------------------- /State/State.cpp: -------------------------------------------------------------------------------- 1 | //g++ State.cpp -Wc++11-extensions -std=c++11 2 | #include 3 | #include 4 | class State; 5 | class Context{ 6 | private: 7 | std::shared_ptr _state; 8 | public: 9 | Context(){ 10 | _state = nullptr; 11 | } 12 | void setState(const std::shared_ptr &state){ 13 | _state = state; 14 | } 15 | std::shared_ptr getState(){ 16 | return _state; 17 | } 18 | }; 19 | class State:public std::enable_shared_from_this{ 20 | public: 21 | virtual void doAction(const std::shared_ptr &context) = 0; 22 | virtual std::string toString() = 0; 23 | }; 24 | 25 | 26 | class StartState : public State{ 27 | public: 28 | void doAction(const std::shared_ptr &context){ 29 | std::cout<<"Player is in start state"<setState(std::shared_ptr(shared_from_this())); 31 | } 32 | 33 | std::string toString(){ 34 | return "Start State"; 35 | } 36 | }; 37 | 38 | class StopState : public State{ 39 | public: 40 | void doAction(const std::shared_ptr &context){ 41 | std::cout<<"Player is in stop state"<setState(std::shared_ptr(shared_from_this())); 43 | } 44 | 45 | std::string toString(){ 46 | return "Stop State"; 47 | } 48 | }; 49 | 50 | int main(){ 51 | std::shared_ptr context = std::make_shared(); 52 | 53 | std::shared_ptr startstate = std::make_shared(); 54 | startstate->doAction(context); 55 | std::cout<getState()->toString()< stopstate = std::make_shared(); 58 | stopstate->doAction(context); 59 | std::cout<getState()->toString()< 2 | #include 3 | 4 | class CashSuper{ 5 | public: 6 | virtual double acceptCash(double money) = 0; 7 | }; 8 | //正常收费 9 | class CashNormal: public CashSuper{ 10 | public: 11 | double acceptCash(double money) { 12 | return money; 13 | } 14 | }; 15 | //打折 16 | class CashRebate: public CashSuper{ 17 | public: 18 | CashRebate(double moneyRebate){ 19 | _moneyRebate = moneyRebate; 20 | } 21 | double acceptCash(double money) { 22 | return money*_moneyRebate; 23 | } 24 | 25 | private: 26 | double _moneyRebate; 27 | }; 28 | 29 | class CashContext{ 30 | public: 31 | CashContext(const std::shared_ptr &cs){ 32 | _cs = cs; 33 | } 34 | double GetResult(double money){ 35 | return _cs->acceptCash(money); 36 | } 37 | private: 38 | std::shared_ptr _cs; 39 | }; 40 | 41 | 42 | int main(){ 43 | auto ptr = std::make_shared(); 44 | auto rv = ptr->acceptCash(100); 45 | std::cout<<"Normal Cash is "<(rebate); 50 | auto rv2 = ptr2->acceptCash(100); 51 | std::cout<<"Rebate Cash (0.8) is "< 3 | #include 4 | 5 | class Game{ 6 | protected: 7 | virtual void initialize() = 0; 8 | virtual void startPlay() = 0; 9 | virtual void endPlay() = 0; 10 | 11 | public: 12 | 13 | virtual void play () final{ 14 | initialize(); 15 | startPlay(); 16 | endPlay(); 17 | } 18 | }; 19 | 20 | class Football : public Game{ 21 | protected: 22 | 23 | void initialize(){ 24 | std::cout<<"start football game."< football = std::make_shared(); 53 | football->play(); 54 | 55 | std::shared_ptr pingpong = std::make_shared(); 56 | pingpong->play(); 57 | 58 | return 0; 59 | } -------------------------------------------------------------------------------- /Visitor/Visitor.cpp: -------------------------------------------------------------------------------- 1 | //g++ Visitor.cpp -Wc++11-extensions -std=c++11 2 | 3 | #include 4 | #include 5 | 6 | class ComputerPartVisitor; 7 | 8 | class ComputerPart { 9 | public: 10 | virtual void accept(const ComputerPartVisitor *computerPartVisitor) = 0; 11 | }; 12 | 13 | class Mouse; 14 | class Keyboard; 15 | class Monitor; 16 | class Computer; 17 | 18 | class ComputerPartVisitor { 19 | public: 20 | virtual void visit(const Computer *computer) const= 0; 21 | virtual void visit(const Mouse *mouse) const = 0; 22 | virtual void visit(const Keyboard *keyboard) const = 0; 23 | virtual void visit(const Monitor *monitor) const = 0; 24 | }; 25 | 26 | 27 | class ComputerPartDisplayVisitor:public ComputerPartVisitor { 28 | public: 29 | void visit(const Computer *computer) const override{ 30 | std::cout<<"Displaying Computer."<visit(this); 50 | } 51 | }; 52 | class Monitor:public ComputerPart { 53 | public: 54 | void accept(const ComputerPartVisitor *computerPartVisitor) override{ 55 | computerPartVisitor->visit(this); 56 | } 57 | }; 58 | class Mouse:public ComputerPart { 59 | public: 60 | void accept(const ComputerPartVisitor *computerPartVisitor)override{ 61 | computerPartVisitor->visit(this); 62 | } 63 | }; 64 | 65 | class Computer:public ComputerPart { 66 | public: 67 | std::vector > parts; 68 | Computer(){ 69 | parts.push_back(std::make_shared()); 70 | parts.push_back(std::make_shared()); 71 | parts.push_back(std::make_shared()); 72 | } 73 | void accept(const ComputerPartVisitor *computerPartVisitor){ 74 | for(auto part:parts){ 75 | part->accept(computerPartVisitor); 76 | } 77 | computerPartVisitor->visit(this); 78 | } 79 | }; 80 | 81 | int main() 82 | { 83 | ComputerPart *computer = new Computer(); 84 | computer->accept(new ComputerPartDisplayVisitor()); 85 | return 0; 86 | } --------------------------------------------------------------------------------