Design mode 2-structural mode

Source: Internet
Author: User

A structured pattern is used to handle a combination of classes or objects, consisting mainly of the following 7 design patterns:
1. The proxy pattern is to provide a proxy for other objects to control access to the object.
2. Decorator mode (Decorator pattern) dynamically adds some additional responsibilities to an object. This mode is more flexible than generating subclasses as far as adding functionality is concerned.
3. The adapter mode (Adapter pattern) is the conversion of one class's interface into another interface that the customer wants. Those classes that would otherwise not work together because of incompatible interfaces can work together.
4. The combined mode (Composite pattern) is a hierarchical structure that combines objects into a tree structure to represent a "partial-whole". Makes the user consistent with the use of individual objects and composite objects.
5. Bridging mode (bridge pattern) separates the abstract part from the actual part so that they can all be changed independently.
6. The appearance pattern (facade pattern) provides a consistent interface for a set of interfaces in a subsystem that defines a high-level interface that makes this subsystem easier to use.
7. Enjoy meta mode (Flyweight pattern) is a shared way of efficiently supporting a large number of fine-grained objects.

1. Proxy mode
#include <iostream> #include <stdlib.h>using namespace std;//////////////////////////////////////////// * Provides a proxy for other objects to control access to this object. (It is to inject a class into another class, that is, as a parameter, or a member) *///////////////////////////////////////////////////////////////////////////class Bookshop//Bookstore {public:virtual ~bookshop () {}virtual void Sailbook () = 0;//supply Book Interface Protected:private:};class Realbookshop: Public Bookshop//entity bookstore {public:virtual void Sailbook () {cout << "entity bookstore selling book" << Endl;} protected:private:};///////////////////////////////////////////////////////////////////////////* Implementation Method 1 does not inherit the parent class */ Class Dangdangproxy//Dangdang agent sells books, also sells other things {Public:~dangdangproxy () {Delete Book;book = NULL;} void Sailbook () {book = new Realbookshop;//A method that invokes a subclass by a pointer to the parent class. Book->sailbook (); Sailshose (); void Sailshose () {cout << "selling Shoes" << Endl;} Protected:private:BookShop *book;};/ * Implementation Method 2 inherits the parent class, inherits the parent class, You can implement a method that invokes a subclass through a pointer or reference to a parent class, */class TaoBao:pUblic Bookshop{public:~taobao () {Delete Book;book = NULL;} virtual void Sailbook () {book = new Realbookshop;//A method that invokes a subclass by a pointer to the parent class. Dazhe (); Book->sailbook ();d Azhe (); void Dazhe () {cout << "holiday discount" << Endl;} Protected:private:BookShop *book;};/ * cocos2d is using proxy mode */////// Class protocol{public:virtual bool Applicationdidfinish () = 0;protected:private:};class application:p ublic protocol{public:application (); int run (); Static application *pointerapp;static application* Getpointerapp ();p rotected:private:}; application* application::p Ointerapp = NULL; Static variable initialization application::application ()//constructor {Pointerapp = this;//static variable assignment}application* Application::getpointerapp () { return Pointerapp;} int Application::Run () {applicationdidfinish (); return 0;} Class Appdelegate:private application//Note is private inheritance {public:virtual bool Applicationdidfinish ();p Rotected:private:};bool appdelegate::applicationdidfinish () {cout << "start Game" << Endl;return true;} int main () {cout << "-----------Dangdang------------" << endl;dangdangproxy Dangdang;dangdang.sailbook (); cout << "-----------TaoBao------------" << Endl; bookshop* book = new Taobao;book->sailbook ();d elete book;cout << "------------coco2d entrance function Analysis------------" <& Lt Endl Appdelegate AppDelete; Application::getpointerapp ()->run (); System ("pause"); return 0;}

2. Decorator Mode
#include <iostream> #include <stdio.h> #include <stdlib.h>using namespace std;/////////////////////    * Decoration (Decorator) mode is also called packing mode.    The ability to extend an object in a transparent manner to the client is an alternative to the inheritance relationship.    Decorating mode is to put the additional functions to be added in a separate class, and let the class contains the object it is to decorate, when it is necessary to execute, the client can selectively, sequentially use the decorative function to wrap the object. is to declare a pointer to a parent class in a class, point to another subclass with a pointer to the parent class, and call the function of that subclass *////////////////////////////////////////////////////////////////    Class Car//car {public:virtual void show () = 0; Virtual ~car () {}protected:private:};class runcar:public car//sports car {public:runcar (car* car = NULL) {This-&gt    ; m_car = car;        } ~runcar () {delete m_car;    M_car = NULL;        } virtual void Show () {if (M_car! = NULL) m_car->show ();    Run ();    } void Run () {cout << "can run" << Endl; }protected:private:car *m_car;};    Class Swimcar:public Car{public:swimcar (car *car=null) {This->m_car = car; } ~SWImcar () {delete m_car;    M_car = NULL;    } void Swim () {cout << "can swim" << Endl;        } virtual void Show () {if (m_car!=null) m_car->show ();    Swim (); }protected:private:car *m_car;};    Class Flycar:public Car{public:flycar (car *car) {This->m_car = car;        } ~flycar () {delete m_car;    M_car = NULL;    } void Fly () {cout << "flying" << Endl;        } virtual void Show () {if (This->m_car! = NULL) m_car->show ();    Fly (); }protected:private:car *m_car;};    int main () {car* myCar = NULL;    MyCar = new Runcar;    Mycar->show ();    cout << "--------------------" << Endl;    flycar* Flycar = new Flycar (MyCar);    Flycar->show ();    cout << "--------------------" << Endl;    Swimcar *swimcar = new Swimcar (Flycar);    Swimcar->show ();    System ("pause"); Delete Swimcar;    Swimcar = NULL; Delete Flycar; FlycaR = NULL; Delete MyCar;    MyCar = NULL; return 0;}
3. Adapter Mode
#include <stdio.h> #include <stdlib.h> #include <iostream>using namespace std;/////////////////////    * Adapter mode is also called the adapter mode, is one of the stereotypes, through the adapter mode can change the existing class (or external Class) interface form.    Applies to: is to convert the interface of a class into another interface that the customer wants.    Those classes that would otherwise not work together because of incompatible interfaces can work together. 220v Voltage <----mutually adaptable----> 110v voltage *///////////////////////////////////////////////////////////////////////////  Class Dianya{public:protected:int V;//extension: can use V to represent voltage, change the value of v};class current220v:virtual public dianya{public:virtual    void use220v () {cout << "220V voltage" << Endl;  }protected:private:};class current110v:virtual public dianya{public:virtual void use110v () {cout <<    "110V voltage" << Endl; }protected:private:};class adapter:public current110v, public current220v{public:adapter () {M_110V = NULL        ;    m_220v = NULL;    } Adapter (current110v* m_110v) {this->m_110v = m_110v; } Adapter (Current220v* m_220v) {this->m_220v = m_220v;             } virtual void use110v () {if (m_220v! = NULL) {cout << adapter fit 220V "<< Endl;        m_220v->use220v ();    } else cout << "110V" << Endl;             } virtual void use220v () {if (m_110v! = NULL) {cout << adapter fit 110V "<< Endl;        m_110v->use110v ();    } else cout << "220V" << Endl;    }protected:private:current110v* m_110v; Current220v* m_220v;};    int main () {current110v* current110v=new current110v;    current220v* current220v=new current220v;    adapter* ADAP = NULL; ADAP = new Adapter (current110v); Input 110V adap->use220v (); After the adapter, output 220V delete adap;    ADAP = NULL; ADAP = new Adapter (current220v); Input 220V adap->use110v (); After the adapter, output 110V delete adap;    ADAP = NULL; Delete current220v;    current220v = NULL; Delete current110v;    current110v = NULL; SYstem ("pause"); return 0;}
4. Combination mode
#include <stdlib.h> #include <stdio.h> #include <iostream> #include <list> #include <string >using namespace std;///////////////////////////////////////////////////////////////////////////* Composite mode is also called the combination mode, is one of the structural design patterns. The structure of the tree object is constructed by means of recursion, and the entire object tree can be accessed through an object. *///////////////////////////////////////////////////////////////////////////class IFile{public:virtual Void Dispaly () = 0;virtual int Add (IFile *ifile) = 0;virtual int Remove (ifile* IFile) = 0;virtual list<ifile*>* Getchild ( ) = 0;protected:private:};//file Node class file:public Ifile{public:file (string filename) {this->m_filename = filename;} virtual void Dispaly () {cout << "file name:" << m_filename << Endl;} virtual int Add (IFile *ifile) {return-1;} virtual int Remove (ifile* IFile) {return-1;} Virtual list<ifile*>* Getchild () {return NULL;} Protected:private:string m_filename;};/ /directory Node class Dir:public Ifile{public:dir (String dirName) {this->m_dirname = Dirname;this->m_list = new List< ifile* > M_list->clear ();} virtual void Dispaly () {cout << "folder name:" << m_dirname << Endl;} virtual int Add (IFile *ifile) {m_list->push_back (IFile); return 0;} virtual int Remove (ifile* IFile) {m_list->remove (IFile); return 0;} Virtual list<ifile*>* Getchild () {return m_list;} Protected:private:string m_dirname;list<ifile*>* m_list;};/  /level is used to control the display hierarchy void ShowTree (ifile* root,int levels) {int i = 0;if (root = = NULL) return;for (i = 0; i <; i++) cout << "\ t"; root->dispaly (); Show root node//2 joghen nodes have children//interpretation child is file, show name)//Judge child is directory, ShowTree (subdirectory) list<ifile*> *mylist = Root->getchild (); if (myList ! = NULL)//description is a directory {for (List<ifile*>::iterator it = Mylist->begin (); It! = Mylist->end (); it++) {if ((*it)- >getchild () = NULL)//File Direct print {for (i = 0; I <= level; i++)//Note <= {printf ("\ t");} (*it)->dispaly ();} else{//directory again recursive call, Level plus 1showTree (*it, level+1);}}} int main () {dir* root = new Dir ("C"); Root->dispaly (); File *fileaaa = new FIle ("Aaa.txt"); File *FILEBBB = new file ("Bbb.txt"); File *FILECCC = new file ("Ccc.txt");D ir *dir001 = new Dir ("001");D ir *dir002 = new Dir ("002");D ir* dir003 = new Dir ("003") , Root->add (dir001), Root->add (dir002), Root->add (FILEAAA);d ir002->add (dir003);d Ir002->add (filebbb );d Ir003->add (FILECCC), list<ifile*>* myList = Root->getchild (); for (list<ifile *>::iterator it = Mylist->begin (); It! = Mylist->end (); it++) {(*it)->dispaly ();} cout << "Show all sub-nodes under root node in showTree mode" << endl;showtree (root, 0); System ("pause"); return 0;}
5. Bridging mode
#include <stdio.h> #include <stdlib.h> #include <iostream>using namespace std;///////////////////// * Bridging mode: is a many-to-many relationship; The engine is available in various models, Cars also have multiple brands each model of the engine can be used by each model of the car can also use each model of the engine is equal to a bridge in the middle, (in the abstract class declaration another abstract class pointer, used to invoke another abstract class subclass method) *//////////////// Class Car; Forward declaration class engine{public:virtual void Enginetype () = 0;protected:car* car;private:};class Type2900:p ublic engine{ public:virtual void Enginetype () {cout << "2900 model engine" << Endl;} Protected:private:};class Type3500:p ublic engine{public:virtual void Enginetype () {cout << "3500 model Engine" << Endl;} Protected:private:};class Type7200:p ublic engine{public:virtual void Enginetype () {cout << "7200 model Engine" << Endl;} Protected:private:};class car{public:virtual void cartype () = 0; Car (engine* engine) {this->m_engine = engine;} Protected:engine *m_engine;private:};class bmw:public CAR{PUBLIC:BMW (Engine* engine): Car (engine) {}virtual void Cartype () {cout << "BMW Car:"; M_engine->enginetype ();} Protected:private:};class jeep:public Car{public:jeep (engine* engine): Car (engine) {}virtual void Cartype () {cout <& Lt "Jeep Car:"; M_engine->enginetype ();} Protected:private:};int Main () {engine*engine = NULL; car* car = Null;engine = new Type2900;car = new BMW (engine), Car->cartype ();d elete car; car = Null;delete engine; engine = Null;engine = new Type3500;car = new BMW (engine), Car->cartype ();d elete car; car = Null;delete engine; engine = Null;engine = new Type3500;car = new Jeep (engine), Car->cartype ();d elete car; car = Null;delete engine; Engine = Null;system ("pause"); return 0;}
6. Appearance mode
#include <stdlib.h> #include <stdio.h> #include <iostream>using namespace std;///////////////////// * Appearance mode is the encapsulation of a layer of shell, providing a unified operating interface is the "operation of similar classes" injected into another class, providing a unified operation */// Class Subsystema{public:void DoSomething () {cout << "Subsystema run" << Endl;} Protected:private:};class subsystemb{public:void dosomething () {cout << "subsystemb run" << Endl;} Protected:private:};class subsystemc{public:void dosomething () {cout << "subsystemc run" << Endl;} Protected:private:};class Facade{public:facade () {Sysa = new SUBSYSTEMA;SYSB = new SUBSYSTEMB;SYSC = new SubSystemC;} ~facade () {delete Sysa;delete sysb;delete SYSC;} void DoSomething () {sysa->dosomething (); sysb->dosomething (); sysc->dosomething ();} Protected:private:SubSystemA *sysa; Subsystemb *SYSB; Subsystemc *SYSC;}; int main () {cout << "how to call without Facade class" << Endl; Subsystema *sysA = new Subsystema; Subsystemb *SYSB = new Subsystemb; SUBSYSTEMC *SYSC = new subsystemc;sysa->dosomething (); sysb->dosomething (); sysc->dosomething ();d elete SysA; Delete Sysb;delete sysc;cout << "invoke with facade class" << Endl; Facade *f = new facade;f->dosomething ();d elete f;system ("pause");}
7. Enjoy meta mode
#include <stdlib.h> #include <stdio.h> #include <iostream> #include <map> #include <string >using namespace std;///////////////////////////////////////////////////////////////////////////* The flyweight mode, also known as the enjoy meta-mode, is one of the stereotype patterns that reduces memory consumption by sharing data with other similar objects. The so-called "enjoy the meta-mode" is to have the same without the tube, not the same continue to add. Only need to be added when judging if there is no same. *///////////////////////////////////////////////////////////////////////////class Person{public:Person (string Name, int age): M_name (name), M_age (age) {}virtual void Printt () = 0;protected:string M_name;int m_age;private:};class Tea Cher:public person{public:teacher (string name, int age, string id):P Erson (name, age), m_id (id) {}virtual void Printt () {Co UT << "name:" << m_name << "Age:" << m_age << "m_id:" << m_id << Endl; Protected:private:string m_id;}; Class Flyweightteacher{public:flyweightteacher () {mapteachers.clear ();} ~flyweightteacher () {while (!mapteachers.empty ()) {Person *tmp = null;map<string, person *>::iterator it = MapteacheRs.begin (); tmp = It->second;mapteachers.erase (IT); Remove the first node from the container delete tmp;}} person* Getteacher (string id) {person* tmp = null;map<string, Person*>::iterator it;it = Mapteachers.find (ID); it = = Mapteachers.end ())//not found {string tmpname;int tmpage;cout << "\ n Enter Teacher's name:"; Cin >> Tmpname;cout < < "\ n input Teacher's age:"; cin >> tmpage;tmp = new Teacher (tmpname,tmpage,id); Mapteachers.insert (Pair<string,person *> (Id,tmp));} Else{tmp = It->second;} return TMP;} Protected:private:map<string, person*> mapteachers;}; int main () {person *p1 = NULL; Person *p2 = NULL; Flyweightteacher * Fwty = new Flyweightteacher;p1->printt ();p 2 = Fwty->getteacher ("001");p 2->printt ();d elete Fwty;system ("pause"); return 0;}








Design mode 2-structural mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.