A design pattern is neither a static solution, nor is it an algorithm. A pattern is a way to describe and address by name (mostly a simplistic description of its goal), a repeatable solution or approach to a common design problem, that is, a common way to solve a generic problem (how generic or complex, depends on how restricted the target goal is). Patterns can emerge on their own or by design. This is why design patterns are useful as an abstraction over the implementation and a help at design stage. With this concept, an easier way to facilitate communication over a design choice as normalization technique is given so that every person can share the design concept.

Depending on the design problem they address, design patterns can be classified in different categories, of which the main categories are:

Patterns are commonly found in objected-oriented programming languages like C++ or Java. They can be seen as a template for how to solve a problem that occurs in many different situations or applications. It is not code reuse, as it usually does not specify code, but code can be easily created from a design pattern. Object-oriented design patterns typically show relationships and interactions between classes or objects without specifying the final application classes or objects that are involved.

Each design pattern consists of the following parts:

Problem/requirement

To use a design pattern, we need to go through a mini analysis design that may be coded to test out the solution. This section states the requirements of the problem we want to solve. This is usually a common problem that will occur in more than one application.

Forces

This section states the technological boundaries, that helps and guides the creation of the solution.

Solution

This section describes how to write the code to solve the above problem. This is the design part of the design pattern. It may contain class diagrams, sequence diagrams, and or whatever is needed to describe how to code the solution.

Design patterns can be considered as a standardization of commonly agreed best practices to solve specific design problems. One should understand them as a way to implement good design patterns within applications. Doing so will reduce the use of inefficient and obscure solutions[citation needed]. Using design patterns speeds up your design and helps to communicate it to other programmers[citation needed].

In software engineering, creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation.

In this section of the book we assume that the reader has enough familiarity with functions, global variables, stack vs. heap, classes, pointers, and static member functions as introduced before.

As we will see there are several creational design patterns, and all will deal with a specific implementation task, that will create a higher level of abstraction to the code base, we will now cover each one.

The Builder Creational Pattern is used to separate the construction of a complex object from its representation so that the same construction process can create different objects representations.

Problem

We want to construct a complex object, however we do not want to have a complex constructor member or one that would need many arguments.

Solution

Define an intermediate object whose member functions define the desired object part by part before the object is available to the client. Builder Pattern lets us defer the construction of the object until all the options for creation have been specified.

Definition: A utility class that creates an instance of several families of classes. It can also return a factory for a certain group.

The Factory Design Pattern is useful in a situation that requires the creation of many different types of objects, all derived from a common base type. The Factory Method defines a method for creating the objects, which subclasses can then override to specify the derived type that will be created. Thus, at run time, the Factory Method can be passed a description of a desired object (e.g., a string read from user input) and return a base class pointer to a new instance of that object. The pattern works best when a well-designed interface is used for the base class, so there is no need to cast the returned object.

Problem

We want to decide at run time what object is to be created based on some configuration or application parameter. When we write the code, we do not know what class should be instantiated.

Solution

Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

In the following example, a factory method is used to create laptop or desktop computer objects at run time.

Let's start by defining Computer, which is an abstract base class (interface) and its derived classes: Laptop and Desktop.

classComputer{public:virtualvoidRun()=0;virtualvoidStop()=0;virtual~Computer(){};/* without this, you do not call Laptop or Desktop destructor in this example! */};classLaptop:publicComputer{public:voidRun()override{mHibernating=false;};voidStop()override{mHibernating=true;};virtual~Laptop(){};/* because we have virtual functions, we need virtual destructor */private:boolmHibernating;// Whether or not the machine is hibernating};classDesktop:publicComputer{public:voidRun()override{mOn=true;};voidStop()override{mOn=false;};virtual~Desktop(){};private:boolmOn;// Whether or not the machine has been turned on};

The actual ComputerFactory class returns a Computer, given a real world description of the object.

Let's analyze the benefits of this design. First, there is a compilation benefit. If we move the interface Computer into a separate header file with the factory, we can then move the implementation of the NewComputer() function into a separate implementation file. Now the implementation file for NewComputer() is the only one that requires knowledge of the derived classes. Thus, if a change is made to any derived class of Computer, or a new Computer subtype is added, the implementation file for NewComputer() is the only file that needs to be recompiled. Everyone who uses the factory will only care about the interface, which should remain consistent throughout the life of the application.

Also, if there is a need to add a class, and the user is requesting objects through a user interface, no code calling the factory may be required to change to support the additional computer type. The code using the factory would simply pass on the new string to the factory, and allow the factory to handle the new types entirely.

Imagine programming a video game, where you would like to add new types of enemies in the future, each of which has different AI functions and can update differently. By using a factory method, the controller of the program can call to the factory to create the enemies, without any dependency or knowledge of the actual types of enemies. Now, future developers can create new enemies, with new AI controls and new drawing member functions, add it to the factory, and create a level which calls the factory, asking for the enemies by name. Combine this method with an XML description of levels, and developers could create new levels without having to recompile their program. All this, thanks to the separation of creation of objects from the usage of objects.

Another example:

#include<stdexcept>#include<iostream>#include<memory>usingnamespacestd;classPizza{public:virtualintgetPrice()const=0;virtual~Pizza(){};/* without this, no destructor for derived Pizza's will be called. */};classHamAndMushroomPizza:publicPizza{public:virtualintgetPrice()const{return850;};virtual~HamAndMushroomPizza(){};};classDeluxePizza:publicPizza{public:virtualintgetPrice()const{return1050;};virtual~DeluxePizza(){};};classHawaiianPizza:publicPizza{public:virtualintgetPrice()const{return1150;};virtual~HawaiianPizza(){};};classPizzaFactory{public:enumPizzaType{HamMushroom,Deluxe,Hawaiian};staticunique_ptr<Pizza>createPizza(PizzaTypepizzaType){switch(pizzaType){caseHamMushroom:returnmake_unique<HamAndMushroomPizza>();caseDeluxe:returnmake_unique<DeluxePizza>();caseHawaiian:returnmake_unique<HawaiianPizza>();}throw"invalid pizza type.";}};/** Create all available pizzas and print their prices*/voidpizza_information(PizzaFactory::PizzaTypepizzatype){unique_ptr<Pizza>pizza=PizzaFactory::createPizza(pizzatype);cout<<"Price of "<<pizzatype<<" is "<<pizza->getPrice()<<std::endl;}intmain(){pizza_information(PizzaFactory::HamMushroom);pizza_information(PizzaFactory::Deluxe);pizza_information(PizzaFactory::Hawaiian);}

A prototype pattern is used in software development when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used, for example, when the inherent cost of creating a new object in the standard way (e.g., using the new keyword) is prohibitively expensive for a given application.

Implementation: Declare an abstract base class that specifies a pure virtual clone() method. Any class that needs a "polymorphic constructor" capability derives itself from the abstract base class, and implements the clone() operation.

Here the client code first invokes the factory method. This factory method, depending on the parameter, finds out the concrete class. On this concrete class, the clone() method is called and the object is returned by the factory method.

This is a sample implementation of Prototype method. We have the detailed description of all the components here.

Record class, which is a pure virtual class that has a pure virtual method clone().

CarRecord, BikeRecord and PersonRecord as concrete implementation of a Record class.

An enum RecordType as one to one mapping of each concrete implementation of Record class.

RecordFactory class that has a Factory method CreateRecord(…). This method requires an enum RecordType as parameter and depending on this parameter it returns the concrete implementation of Record class.

To implement the pattern, declare an abstract base class that specifies a pure virtual clone() member function. Any class that needs a "polymorphic constructor" capability derives itself from the abstract base class, and implements the clone() operation.

The client, instead of writing code that invokes the new operator on a hard-wired class name, calls the clone() member function on the prototype, calls a factory member function with a parameter designating the particular concrete derived class desired, or invokes the clone() member function through some mechanism provided by another design pattern.

A client of one of the concrete monster classes only needs a reference (pointer) to a CPrototypeMonster class object to be able to call the ‘Clone’ function and create copies of that object. The function below demonstrates this concept:

voidDoSomeStuffWithAMonster(constCPrototypeMonster*originalMonster){CPrototypeMonster*newMonster=originalMonster->Clone();ASSERT(newMonster);newMonster->Name("MyOwnMonster");// Add code doing all sorts of cool stuff with the monster.deletenewMonster;}

Now originalMonster can be passed as a pointer to CGreenMonster, CPurpleMonster or CBellyMonster.

The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. It is named after the singleton set, which is defined to be a set containing one element. This is useful when exactly one object is needed to coordinate actions across the system.

Check list

Define a private static attribute in the "single instance" class.

Define a public static accessor function in the class.

Do "lazy initialization" (creation on first use) in the accessor function.

Define all constructors to be protected or private.

Clients may only use the accessor function to manipulate the Singleton.

Let's take a look at how a Singleton differs from other variable types.

Like a global variable, the Singleton exists outside of the scope of any functions. Traditional implementation uses a static member function of the Singleton class, which will create a single instance of the Singleton class on the first call, and forever return that instance. The following code example illustrates the elements of a C++ singleton class, that simply stores a single string.

classStringSingleton{public:// Some accessor functions for the class, itselfstd::stringGetString()const{returnmString;}voidSetString(conststd::string&newStr){mString=newStr;}// The magic function, which allows access to the class from anywhere// To get the value of the instance of the class, call:// StringSingleton::Instance().GetString();staticStringSingleton&Instance(){// This line only runs once, thus creating the only instance in existencestaticStringSingleton*instance=newStringSingleton;// dereferencing the variable here, saves the caller from having to use // the arrow operator, and removes temptation to try and delete the // returned instance.return*instance;// always returns the same instance}private:// We need to make some given functions private to finish the definition of the singletonStringSingleton(){}// default constructor available only to members or friends of this class// Note that the next two functions are not given bodies, thus any attempt // to call them implicitly will return as compiler errors. This prevents // accidental copying of the only instance of the class.StringSingleton(constStringSingleton&old);// disallow copy constructorconstStringSingleton&operator=(constStringSingleton&old);//disallow assignment operator// Note that although this should be allowed, // some compilers may not implement private destructors// This prevents others from deleting our one single instance, which was otherwise created on the heap~StringSingleton(){}private:// private data for an instance of this classstd::stringmString;};

Variations of Singletons:

To do:
Discussion of Meyers Singleton and any other variations.

Applications of Singleton Class:

One common use of the singleton design pattern is for application configurations. Configurations may need to be accessible globally, and future expansions to the application configurations may be needed. The subset C's closest alternative would be to create a single global struct. This had the lack of clarity as to where this object was instantiated, as well as not guaranteeing the existence of the object.

Take, for example, the situation of another developer using your singleton inside the constructor of their object. Then, yet another developer decides to create an instance of the second class in the global scope. If you had simply used a global variable, the order of linking would then matter. Since your global will be accessed, possibly before main begins executing, there is no definition as to whether the global is initialized, or the constructor of the second class is called first. This behavior can then change with slight modifications to other areas of code, which would change order of global code execution. Such an error can be very hard to debug. But, with use of the singleton, the first time the object is accessed, the object will also be created. You now have an object which will always exist, in relation to being used, and will never exist if never used.

A second common use of this class is in updating old code to work in a new architecture. Since developers may have used globals liberally, moving them into a single class and making it a singleton, can be an intermediary step to bring the program inline to stronger object oriented structure.

Another example:

#include<iostream>usingnamespacestd;/* Place holder for thread synchronization mutex */classMutex{/* placeholder for code to create, use, and free a mutex */};/* Place holder for thread synchronization lock */classLock{public:Lock(Mutex&m):mutex(m){/* placeholder code to acquire the mutex */}~Lock(){/* placeholder code to release the mutex */}private:Mutex&mutex;};classSingleton{public:staticSingleton*GetInstance();inta;~Singleton(){cout<<"In Destructor"<<endl;}private:Singleton(int_a):a(_a){cout<<"In Constructor"<<endl;}staticMutexmutex;// Not defined, to prevent copyingSingleton(constSingleton&);Singleton&operator=(constSingleton&other);};MutexSingleton::mutex;Singleton*Singleton::GetInstance(){Locklock(mutex);cout<<"Get Instance"<<endl;// Initialized during first accessstaticSingletoninst(1);return&inst;}intmain(){Singleton*singleton=Singleton::GetInstance();cout<<"The value of the singleton: "<<singleton->a<<endl;return0;}

Note:
In the above example, the first call to Singleton::GetInstance will initialize the singleton instance. This example is for illustrative purposes only; for anything but a trivial example program, this code contains errors.

Convert the interface of a class into another interface that clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

#include<iostream>classMuslim{// Abstract Targetpublic:virtual~Muslim()=default;virtualvoidperformsMuslimRitual()const=0;};classMuslimFemale:publicMuslim{// Concrete Targetpublic:virtualvoidperformsMuslimRitual()constoverride{std::cout<<"Muslim girl performs Muslim ritual."<<std::endl;}};classHindu{// Abstract Adapteepublic:virtual~Hindu()=default;virtualvoidperformsHinduRitual()const=0;};classHinduFemale:publicHindu{// Concrete Adapteepublic:virtualvoidperformsHinduRitual()constoverride{std::cout<<"Hindu girl performs Hindu ritual."<<std::endl;}};classMuslimRitual{public:voidcarryOutRitual(Muslim*muslim){std::cout<<"On with the Muslim rituals!"<<std::endl;muslim->performsMuslimRitual();}};classMuslimAdapter:publicMuslim{// Adapterprivate:Hindu*hindu;public:MuslimAdapter(Hindu*h):hindu(h){}virtualvoidperformsMuslimRitual()constoverride{hindu->performsHinduRitual();}};intmain(){// Client codeHinduFemale*hinduGirl=newHinduFemale;MuslimFemale*muslimGirl=newMuslimFemale;MuslimRitualmuslimRitual;// muslimRitual.carryOutRitual (hinduGirl); // Will not compile of course since the parameter must be of type Muslim*.MuslimAdapter*adaptedHindu=newMuslimAdapter(hinduGirl);// hinduGirl has adapted to become a Muslim!muslimRitual.carryOutRitual(muslimGirl);muslimRitual.carryOutRitual(adaptedHindu);// So now hinduGirl, in the form of adaptedHindu, participates in the muslimRitual!// Note that hinduGirl is carrying out her own type of ritual in muslimRitual though.deleteadaptedHindu;// adaptedHindu is not needed anymoredeletehinduGirl;// hinduGirl is not needed anymoredeletemuslimGirl;// muslimGirl is not needed anymore, tooreturn0;}

Composite lets clients treat individual objects and compositions of objects uniformly. The Composite pattern can represent both the conditions. In this pattern, one can develop tree structures for representing part-whole hierarchies.

The decorator pattern helps to attach additional behavior or responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. This is also called “Wrapper”. If your application does some kind of filtering, then Decorator might be good pattern to consider for the job.

#include<string>#include<iostream>usingnamespacestd;classCar//Our Abstract base class{protected:string_str;public:Car(){_str="Unknown Car";}virtualstringgetDescription(){return_str;}virtualdoublegetCost()=0;virtual~Car(){cout<<"~Car()\n";}};classOptionsDecorator:publicCar//Decorator Base class{public:virtualstringgetDescription()=0;virtual~OptionsDecorator(){cout<<"~OptionsDecorator()\n";}};classCarModel1:publicCar{public:CarModel1(){_str="CarModel1";}virtualdoublegetCost(){return31000.23;}~CarModel1(){cout<<"~CarModel1()\n";}};classNavigation:publicOptionsDecorator{Car*_b;public:Navigation(Car*b){_b=b;}stringgetDescription(){return_b->getDescription()+", Navigation";}doublegetCost(){return300.56+_b->getCost();}~Navigation(){cout<<"~Navigation()\n";}};classPremiumSoundSystem:publicOptionsDecorator{Car*_b;public:PremiumSoundSystem(Car*b){_b=b;}stringgetDescription(){return_b->getDescription()+", PremiumSoundSystem";}doublegetCost(){return0.30+_b->getCost();}~PremiumSoundSystem(){cout<<"~PremiumSoundSystem()\n";}};classManualTransmission:publicOptionsDecorator{Car*_b;public:ManualTransmission(Car*b){_b=b;}stringgetDescription(){return_b->getDescription()+", ManualTransmission";}doublegetCost(){return0.30+_b->getCost();}~ManualTransmission(){cout<<"~ManualTransmission()\n";}};intmain(){//Create our Car that we want to buyCar*b=newCarModel1();cout<<"Base model of "<<b->getDescription()<<" costs $"<<b->getCost()<<"\n";//Who wants base model let's add some more featuresb=newNavigation(b);cout<<b->getDescription()<<" will cost you $"<<b->getCost()<<"\n";b=newPremiumSoundSystem(b);b=newManualTransmission(b);cout<<b->getDescription()<<" will cost you $"<<b->getCost()<<"\n";// WARNING! Here we leak the CarModel1, Navigation and PremiumSoundSystem objects!// Either we delete them explicitly or rewrite the Decorators to take // ownership and delete their Cars when destroyed.deleteb;return0;}

#include<iostream>#include<string>#include<memory>classInterface{public:virtual~Interface(){}virtualvoidwrite(std::string&)=0;};classCore:publicInterface{public:~Core(){std::cout<<"Core destructor called.\n";}virtualvoidwrite(std::string&text)override{};// Do nothing.};classDecorator:publicInterface{private:std::unique_ptr<Interface>interface;public:Decorator(std::unique_ptr<Interface>c){interface=std::move(c);}virtualvoidwrite(std::string&text)override{interface->write(text);}};classMessengerWithSalutation:publicDecorator{private:std::stringsalutation;public:MessengerWithSalutation(std::unique_ptr<Interface>c,conststd::string&str):Decorator(std::move(c)),salutation(str){}~MessengerWithSalutation(){std::cout<<"Messenger destructor called.\n";}virtualvoidwrite(std::string&text)override{text=salutation+"\n\n"+text;Decorator::write(text);}};classMessengerWithValediction:publicDecorator{private:std::stringvalediction;public:MessengerWithValediction(std::unique_ptr<Interface>c,conststd::string&str):Decorator(std::move(c)),valediction(str){}~MessengerWithValediction(){std::cout<<"MessengerWithValediction destructor called.\n";}virtualvoidwrite(std::string&text)override{Decorator::write(text);text+="\n\n"+valediction;}};intmain(){conststd::stringsalutation="Greetings,";conststd::stringvalediction="Sincerly, Andy";std::stringmessage1="This message is not decorated.";std::stringmessage2="This message is decorated with a salutation.";std::stringmessage3="This message is decorated with a valediction.";std::stringmessage4="This message is decorated with a salutation and a valediction.";std::unique_ptr<Interface>messenger1=std::make_unique<Core>();std::unique_ptr<Interface>messenger2=std::make_unique<MessengerWithSalutation>(std::make_unique<Core>(),salutation);std::unique_ptr<Interface>messenger3=std::make_unique<MessengerWithValediction>(std::make_unique<Core>(),valediction);std::unique_ptr<Interface>messenger4=std::make_unique<MessengerWithValediction>(std::make_unique<MessengerWithSalutation>(std::make_unique<Core>(),salutation),valediction);messenger1->write(message1);std::cout<<message1<<'\n';std::cout<<"\n------------------------------\n\n";messenger2->write(message2);std::cout<<message2<<'\n';std::cout<<"\n------------------------------\n\n";messenger3->write(message3);std::cout<<message3<<'\n';std::cout<<"\n------------------------------\n\n";messenger4->write(message4);std::cout<<message4<<'\n';std::cout<<"\n------------------------------\n\n";}

The Facade Pattern hides the complexities of the system by providing an interface to the client from where the client can access the system on an unified interface. Facade defines a higher-level interface that makes the subsystem easier to use. For instance making one class method perform a complex process by calling several other classes.

/*Facade is one of the easiest patterns I think... And this is very simple example. Imagine you set up a smart house where everything is on remote. So to turn the lights on you push lights on button - And same for TV,AC, Alarm, Music, etc...When you leave a house you would need to push a 100 buttons to make sure everything is off and are good to go which could be little annoying if you are lazy like me so I defined a Facade for leaving and coming back. (Facade functions represent buttons...) So when I come and leave I just make one call and it takes care of everything...*/#include<string>#include<iostream>usingnamespacestd;classAlarm{public:voidalarmOn(){cout<<"Alarm is on and house is secured"<<endl;}voidalarmOff(){cout<<"Alarm is off and you can go into the house"<<endl;}};classAc{public:voidacOn(){cout<<"Ac is on"<<endl;}voidacOff(){cout<<"AC is off"<<endl;}};classTv{public:voidtvOn(){cout<<"Tv is on"<<endl;}voidtvOff(){cout<<"TV is off"<<endl;}};classHouseFacade{Alarmalarm;Acac;Tvtv;public:HouseFacade(){}voidgoToWork(){ac.acOff();tv.tvOff();alarm.alarmOn();}voidcomeHome(){alarm.alarmOff();ac.acOn();tv.tvOn();}};intmain(){HouseFacadehf;//Rather than calling 100 different on and off functions thanks to facade I only have 2 functions...hf.goToWork();hf.comeHome();}

The output of the program above is:

AC is off
TV is off
Alarm is on and house is secured
Alarm is off and you can go into the house
Ac is on
Tv is on

The pattern for saving memory (basically) by sharing properties of objects. Imagine a huge amount of similar objects which all have most of their properties the same. It's natural to move these properties out of these objects to some external data structure and provide each object with the link to that data structure.

#include<iostream>#include<string>#include<vector>#define NUMBER_OF_SAME_TYPE_CHARS 3;/* Actual flyweight objects class (declaration) */classFlyweightCharacter;/* FlyweightCharacterAbstractBuilder is a class holding the properties which are shared by many objects. So instead of keeping these properties in those objects we keep them externally, making objects flyweight. See more details in the comments of main function.*/classFlyweightCharacterAbstractBuilder{FlyweightCharacterAbstractBuilder(){}~FlyweightCharacterAbstractBuilder(){}public:staticstd::vector<float>fontSizes;// lets imagine that sizes be may of floating point typestaticstd::vector<std::string>fontNames;// font name may be of variable length (lets take 6 bytes is average)staticvoidsetFontsAndNames();staticFlyweightCharactercreateFlyweightCharacter(unsignedshortfontSizeIndex,unsignedshortfontNameIndex,unsignedshortpositionInStream);};std::vector<float>FlyweightCharacterAbstractBuilder::fontSizes(3);std::vector<std::string>FlyweightCharacterAbstractBuilder::fontNames(3);voidFlyweightCharacterAbstractBuilder::setFontsAndNames(){fontSizes[0]=1.0;fontSizes[1]=1.5;fontSizes[2]=2.0;fontNames[0]="first_font";fontNames[1]="second_font";fontNames[2]="third_font";}classFlyweightCharacter{unsignedshortfontSizeIndex;// index instead of actual font sizeunsignedshortfontNameIndex;// index instead of font nameunsignedpositionInStream;public:FlyweightCharacter(unsignedshortfontSizeIndex,unsignedshortfontNameIndex,unsignedshortpositionInStream):fontSizeIndex(fontSizeIndex),fontNameIndex(fontNameIndex),positionInStream(positionInStream){}voidprint(){std::cout<<"Font Size: "<<FlyweightCharacterAbstractBuilder::fontSizes[fontSizeIndex]<<", font Name: "<<FlyweightCharacterAbstractBuilder::fontNames[fontNameIndex]<<", character stream position: "<<positionInStream<<std::endl;}~FlyweightCharacter(){}};FlyweightCharacterFlyweightCharacterAbstractBuilder::createFlyweightCharacter(unsignedshortfontSizeIndex,unsignedshortfontNameIndex,unsignedshortpositionInStream){FlyweightCharacterfc(fontSizeIndex,fontNameIndex,positionInStream);returnfc;}intmain(intargc,char**argv){std::vector<FlyweightCharacter>chars;FlyweightCharacterAbstractBuilder::setFontsAndNames();unsignedshortlimit=NUMBER_OF_SAME_TYPE_CHARS;for(unsignedshorti=0;i<limit;i++){chars.push_back(FlyweightCharacterAbstractBuilder::createFlyweightCharacter(0,0,i));chars.push_back(FlyweightCharacterAbstractBuilder::createFlyweightCharacter(1,1,i+1*limit));chars.push_back(FlyweightCharacterAbstractBuilder::createFlyweightCharacter(2,2,i+2*limit));}/* Each char stores links to it's fontName and fontSize so what we get is: each object instead of allocating 6 bytes (convention above) for string and 4 bytes for float allocates 2 bytes for fontNameIndex and fontSizeIndex. That means for each char we save 6 + 4 - 2 - 2 = 6 bytes. Now imagine we have NUMBER_OF_SAME_TYPE_CHARS = 1000 i.e. with our code we will have 3 groups of chars whith 1000 chars in each group which will save us 3 * 1000 * 6 - (3 * 6 + 3 * 4) = 17970 saved bytes. 3 * 6 + 3 * 4 is a number of bytes allocated by FlyweightCharacterAbstractBuilder. So the idea of the pattern is to move properties shared by many objects to some external container. The objects in that case don't store the data themselves they store only links to the data which saves memory and make the objects lighter. The data size of properties stored externally may be significant which will save REALLY huge ammount of memory and will make each object super light in comparisson to it's counterpart. That's where the name of the pattern comes from: flyweight (i.e. very light). */for(unsignedshorti=0;i<chars.size();i++){chars[i].print();}std::cin.get();return0;}

The Proxy Pattern will provide an object a surrogate or placeholder for another object to control access to it. It is used when you need to represent a complex object with a simpler one. If creation of an object is expensive, it can be postponed until the very need arises and meanwhile a simpler object can serve as a placeholder. This placeholder object is called the “Proxy” for the complex object.

Interface-based programming is closely related with Modular Programming and Object-Oriented Programming, it defines the application as a collection of inter-coupled modules (interconnected and which plug into each other via interface). Modules can be unplugged, replaced, or upgraded, without the need of compromising the contents of other modules.

The total system complexity is greatly reduced. Interface Based Programming adds more to modular Programming in that it insists that Interfaces are to be added to these modules. The entire system is thus viewed as Components and the interfaces that helps them to co-act.

Interface-based Programming increases the modularity of the application and hence its maintainability at a later development cycles, especially when each module must be developed by different teams. It is a well-known methodology that has been around for a long time and it is a core technology behind frameworks such as CORBA.

This is particularly convenient when third parties develop additional components for the established system. They just have to develop components that satisfy the interface specified by the parent application vendor.

Thus the publisher of the interfaces assures that he will not change the interface and the subscriber agrees to implement the interface as whole without any deviation. An interface is therefore said to be a Contractual agreement and the programming paradigm based on this is termed as "interface based programming".

Chain of Responsibility pattern has the intent to avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chains the receiving objects and passes the requests along the chain until an object handles it.

#include<iostream>usingnamespacestd;classHandler{protected:Handler*next;public:Handler(){next=NULL;}virtual~Handler(){}virtualvoidrequest(intvalue)=0;voidsetNextHandler(Handler*nextInLine){next=nextInLine;}};classSpecialHandler:publicHandler{private:intmyLimit;intmyId;public:SpecialHandler(intlimit,intid){myLimit=limit;myId=id;}~SpecialHandler(){}voidrequest(intvalue){if(value<myLimit){cout<<"Handler "<<myId<<" handled the request with a limit of "<<myLimit<<endl;}elseif(next!=NULL){next->request(value);}else{cout<<"Sorry, I am the last handler ("<<myId<<") and I can't handle the request."<<endl;}}};intmain(){Handler*h1=newSpecialHandler(10,1);Handler*h2=newSpecialHandler(20,2);Handler*h3=newSpecialHandler(30,3);h1->setNextHandler(h2);h2->setNextHandler(h3);h1->request(18);h1->request(40);deleteh1;deleteh2;deleteh3;return0;}

Command pattern is an Object behavioral pattern that decouples sender and receiver by encapsulating a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undo-able operations. It can also be thought as an object oriented equivalent of call back method.

Call Back: It is a function that is registered to be called at later point of time based on user actions.

#include<iostream>usingnamespacestd;/*the Command interface*/classCommand{public:virtualvoidexecute()=0;};/*Receiver class*/classLight{public:Light(){}voidturnOn(){cout<<"The light is on"<<endl;}voidturnOff(){cout<<"The light is off"<<endl;}};/*the Command for turning on the light*/classFlipUpCommand:publicCommand{public:FlipUpCommand(Light&light):theLight(light){}virtualvoidexecute(){theLight.turnOn();}private:Light&theLight;};/*the Command for turning off the light*/classFlipDownCommand:publicCommand{public:FlipDownCommand(Light&light):theLight(light){}virtualvoidexecute(){theLight.turnOff();}private:Light&theLight;};classSwitch{public:Switch(Command&flipUpCmd,Command&flipDownCmd):flipUpCommand(flipUpCmd),flipDownCommand(flipDownCmd){}voidflipUp(){flipUpCommand.execute();}voidflipDown(){flipDownCommand.execute();}private:Command&flipUpCommand;Command&flipDownCommand;};/*The test class or client*/intmain(){Lightlamp;FlipUpCommandswitchUp(lamp);FlipDownCommandswitchDown(lamp);Switchs(switchUp,switchDown);s.flipUp();s.flipDown();}

Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.

To do:
It would be good to refer the reader to lex and yacc, and/or its derivatives like flex and bison, for an alternate (time-tested?) approach to these problems.

#include<iostream>#include<string>#include<map>#include<list>namespacewikibooks_design_patterns{// based on the Java sample around heretypedefstd::stringString;structExpression;typedefstd::map<String,Expression*>Map;typedefstd::list<Expression*>Stack;structExpression{virtualintinterpret(Mapvariables)=0;virtual~Expression(){}};classNumber:publicExpression{private:intnumber;public:Number(intnumber){this->number=number;}intinterpret(Mapvariables){returnnumber;}};classPlus:publicExpression{Expression*leftOperand;Expression*rightOperand;public:Plus(Expression*left,Expression*right){leftOperand=left;rightOperand=right;}~Plus(){deleteleftOperand;deleterightOperand;}intinterpret(Mapvariables){returnleftOperand->interpret(variables)+rightOperand->interpret(variables);}};classMinus:publicExpression{Expression*leftOperand;Expression*rightOperand;public:Minus(Expression*left,Expression*right){leftOperand=left;rightOperand=right;}~Minus(){deleteleftOperand;deleterightOperand;}intinterpret(Mapvariables){returnleftOperand->interpret(variables)-rightOperand->interpret(variables);}};classVariable:publicExpression{Stringname;public:Variable(Stringname){this->name=name;}intinterpret(Mapvariables){if(variables.end()==variables.find(name))return0;returnvariables[name]->interpret(variables);}};// While the interpreter pattern does not address parsing, a parser is provided for completeness.classEvaluator:publicExpression{Expression*syntaxTree;public:Evaluator(Stringexpression){StackexpressionStack;size_tlast=0;for(size_tnext=0;String::npos!=last;last=(String::npos==next)?next:(1+next)){next=expression.find(' ',last);Stringtoken(expression.substr(last,(String::npos==next)?(expression.length()-last):(next-last)));if(token=="+"){Expression*right=expressionStack.back();expressionStack.pop_back();Expression*left=expressionStack.back();expressionStack.pop_back();Expression*subExpression=newPlus(right,left);expressionStack.push_back(subExpression);}elseif(token=="-"){// it's necessary remove first the right operand from the stackExpression*right=expressionStack.back();expressionStack.pop_back();// ..and after the left oneExpression*left=expressionStack.back();expressionStack.pop_back();Expression*subExpression=newMinus(left,right);expressionStack.push_back(subExpression);}elseexpressionStack.push_back(newVariable(token));}syntaxTree=expressionStack.back();expressionStack.pop_back();}~Evaluator(){deletesyntaxTree;}intinterpret(Mapcontext){returnsyntaxTree->interpret(context);}};}voidmain(){usingnamespacewikibooks_design_patterns;Evaluatorsentence("w x z - +");staticconstintsequences[][3]={{5,10,42},{1,3,2},{7,9,-5},};for(size_ti=0;sizeof(sequences)/sizeof(sequences[0])>i;++i){Mapvariables;variables["w"]=newNumber(sequences[i][0]);variables["x"]=newNumber(sequences[i][1]);variables["z"]=newNumber(sequences[i][2]);intresult=sentence.interpret(variables);for(Map::iteratorit=variables.begin();variables.end()!=it;++it)deleteit->second;std::cout<<"Interpreter result: "<<result<<std::endl;}}

The 'iterator' design pattern is used liberally within the STL for traversal of various containers. The full understanding of this will liberate a developer to create highly reusable and easily understandable[citation needed] data containers.

The basic idea of the iterator is that it permits the traversal of a container (like a pointer moving across an array). However, to get to the next element of a container, you need not know anything about how the container is constructed. This is the iterators job. By simply using the member functions provided by the iterator, you can move, in the intended order of the container, from the first element to the last element.

Let us start by considering a traditional single dimensional array with a pointer moving from the start to the end. This example assumes knowledge of pointer arithmetic. Note that the use of "it" or "itr," henceforth, is a short version of "iterator."

constintARRAY_LEN=42;int*myArray=newint[ARRAY_LEN];// Set the iterator to point to the first memory location of the arrayint*arrayItr=myArray;// Move through each element of the array, setting it equal to its position in the arrayfor(inti=0;i<ARRAY_LEN;++i){// set the value of the current location in the array*arrayItr=i;// by incrementing the pointer, we move it to the next position in the array.// This is easy for a contiguous memory container, since pointer arithmetic // handles the traversal.++arrayItr;}// Do not be messy, clean up after yourselfdelete[]myArray;

This code works very quickly for arrays, but how would we traverse a linked list, when the memory is not contiguous? Consider the implementation of a rudimentary linked list as follows:

classIteratorCannotMoveToNext{};// Error classclassMyIntLList{public:// The Node class represents a single element in the linked list. // The node has a next node and a previous node, so that the user // may move from one position to the next, or step back a single // position. Notice that the traversal of a linked list is O(N), // as is searching, since the list is not ordered.classNode{public:Node():mNextNode(0),mPrevNode(0),mValue(0){}Node*mNextNode;Node*mPrevNode;intmValue;};MyIntLList():mSize(0){}~MyIntLList(){while(!Empty())pop_front();}// See expansion for further implementation;intSize()const{returnmSize;}// Add this value to the end of the listvoidpush_back(intvalue){Node*newNode=newNode;newNode->mValue=value;newNode->mPrevNode=mTail;mTail->mNextNode=newNode;mTail=newNode;++mSize;}// Remove the value from the beginning of the listvoidpop_front(){if(Empty())return;Node*tmpnode=mHead;mHead=mHead->mNextNode;deletetmpnode;--mSize;}boolEmpty(){returnmSize==0;}// This is where the iterator definition will go, // but lets finish the definition of the list, firstprivate:Node*mHead;Node*mTail;intmSize;};

This linked list has non-contiguous memory, and is therefore not a candidate for pointer arithmetic. And we do not want to expose the internals of the list to other developers, forcing them to learn them, and keeping us from changing it.

This is where the iterator comes in. The common interface makes learning the usage of the container easier, and hides the traversal logic from other developers.

Let us examine the code for the iterator, itself.

/* * The iterator class knows the internals of the linked list, so that it * may move from one element to the next. In this implementation, I have * chosen the classic traversal method of overloading the increment * operators. More thorough implementations of a bi-directional linked * list would include decrement operators so that the iterator may move * in the opposite direction. */classIterator{public:Iterator(Node*position):mCurrNode(position){}// Prefix incrementconstIterator&operator++(){if(mCurrNode==0||mCurrNode->mNextNode==0)throwIteratorCannotMoveToNext();emCurrNode=mCurrNode->mNextNode;return*this;}// Postfix incrementIteratoroperator++(int){IteratortempItr=*this;++(*this);returntempItr;}// Dereferencing operator returns the current node, which should then // be dereferenced for the int. TODO: Check syntax for overloading // dereferencing operatorNode*operator*(){returnmCurrNode;}// TODO: implement arrow operator and clean up example usage followingprivate:Node*mCurrNode;};// The following two functions make it possible to create // iterators for an instance of this class.// First position for iterators should be the first element in the container.IteratorBegin(){returnIterator(mHead);}// Final position for iterators should be one past the last element in the container.IteratorEnd(){returnIterator(0);}

With this implementation, it is now possible, without knowledge of the size of the container or how its data is organized, to move through each element in order, manipulating or simply accessing the data. This is done through the accessors in the MyIntLList class, Begin() and End().

// Create a listMyIntLListmyList;// Add some items to the listfor(inti=0;i<10;++i)myList.push_back(i);// Move through the list, adding 42 to each item.for(MyIntLList::Iteratorit=myList.Begin();it!=myList.End();++it)(*it)->mValue+=42;

To do:

Discussion of iterators in the STL, and the usefulness of iterators within the algorithms library.

Iterators best practices

Warnings on creation of and usage of

When use of operator[] is better and simplifies understanding

Cautions about the impact of templates on generated code size (this could make for a good student research paper)

The following program gives the implementation of an iterator design pattern with a generic template:

Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.

#include<iostream>#include<string>#include<list>classMediatorInterface;classColleagueInterface{std::stringname;public:ColleagueInterface(conststd::string&newName):name(newName){}std::stringgetName()const{returnname;}virtualvoidsendMessage(constMediatorInterface&,conststd::string&)const=0;virtualvoidreceiveMessage(constColleagueInterface*,conststd::string&)const=0;};classColleague:publicColleagueInterface{public:usingColleagueInterface::ColleagueInterface;virtualvoidsendMessage(constMediatorInterface&,conststd::string&)constoverride;private:virtualvoidreceiveMessage(constColleagueInterface*,conststd::string&)constoverride;};classMediatorInterface{private:std::list<ColleagueInterface*>colleagueList;public:conststd::list<ColleagueInterface*>&getColleagueList()const{returncolleagueList;}virtualvoiddistributeMessage(constColleagueInterface*,conststd::string&)const=0;virtualvoidregisterColleague(ColleagueInterface*colleague){colleagueList.emplace_back(colleague);}};classMediator:publicMediatorInterface{virtualvoiddistributeMessage(constColleagueInterface*,conststd::string&)constoverride;};voidColleague::sendMessage(constMediatorInterface&mediator,conststd::string&message)const{mediator.distributeMessage(this,message);}voidColleague::receiveMessage(constColleagueInterface*sender,conststd::string&message)const{std::cout<<getName()<<" received the message from "<<sender->getName()<<": "<<message<<std::endl;}voidMediator::distributeMessage(constColleagueInterface*sender,conststd::string&message)const{for(constColleagueInterface*x:getColleagueList())if(x!=sender)// Do not send the message back to the senderx->receiveMessage(sender,message);}intmain(){Colleague*bob=newColleague("Bob"),*sam=newColleague("Sam"),*frank=newColleague("Frank"),*tom=newColleague("Tom");Colleague*staff[]={bob,sam,frank,tom};MediatormediatorStaff,mediatorSamsBuddies;for(Colleague*x:staff)mediatorStaff.registerColleague(x);bob->sendMessage(mediatorStaff,"I'm quitting this job!");mediatorSamsBuddies.registerColleague(frank);mediatorSamsBuddies.registerColleague(tom);// Sam's buddies onlysam->sendMessage(mediatorSamsBuddies,"Hooray! He's gone! Let's go for a drink, guys!");return0;}

Without violating encapsulation the Memento Pattern will capture and externalize an object’s internal state so that the object can be restored to this state later. Though the Gang of Four uses friend as a way to implement this pattern it is not the best design[citation needed]. It can also be implemented using PIMPL (pointer to implementation or opaque pointer). Best Use case is 'Undo-Redo' in an editor.

The Originator (the object to be saved) creates a snap-shot of itself as a Memento object, and passes that reference to the Caretaker object. The Caretaker object keeps the Memento until such a time as the Originator may want to revert to a previous state as recorded in the Memento object.

#include<iostream>#include<string>#include<sstream>#include<vector>conststd::stringNAME="Object";template<typenameT>std::stringtoString(constT&t){std::stringstreamss;ss<<t;returnss.str();}classMemento;classObject{private:intvalue;std::stringname;doubledecimal;// and suppose there are loads of other data memberspublic:Object(intnewValue):value(newValue),name(NAME+toString(value)),decimal((float)value/100){}voiddoubleValue(){value=2*value;name=NAME+toString(value);decimal=(float)value/100;}voidincreaseByOne(){value++;name=NAME+toString(value);decimal=(float)value/100;}intgetValue()const{returnvalue;}std::stringgetName()const{returnname;}doublegetDecimal()const{returndecimal;}Memento*createMemento()const;voidreinstateMemento(Memento*mem);};classMemento{private:Objectobject;public:Memento(constObject&obj):object(obj){}Objectsnapshot()const{returnobject;}// want a snapshot of Object itself because of its many data members};Memento*Object::createMemento()const{returnnewMemento(*this);}voidObject::reinstateMemento(Memento*mem){*this=mem->snapshot();}classCommand{private:typedefvoid(Object::*Action)();Object*receiver;Actionaction;staticstd::vector<Command*>commandList;staticstd::vector<Memento*>mementoList;staticintnumCommands;staticintmaxCommands;public:Command(Object*newReceiver,ActionnewAction):receiver(newReceiver),action(newAction){}virtualvoidexecute(){if(mementoList.size()<numCommands+1)mementoList.resize(numCommands+1);mementoList[numCommands]=receiver->createMemento();// saves the last valueif(commandList.size()<numCommands+1)commandList.resize(numCommands+1);commandList[numCommands]=this;// saves the last commandif(numCommands>maxCommands)maxCommands=numCommands;numCommands++;(receiver->*action)();}staticvoidundo(){if(numCommands==0){std::cout<<"There is nothing to undo at this point."<<std::endl;return;}commandList[numCommands-1]->receiver->reinstateMemento(mementoList[numCommands-1]);numCommands--;}voidstaticredo(){if(numCommands>maxCommands){std::cout<<"There is nothing to redo at this point."<<std::endl;return;}Command*commandRedo=commandList[numCommands];(commandRedo->receiver->*(commandRedo->action))();numCommands++;}};std::vector<Command*>Command::commandList;std::vector<Memento*>Command::mementoList;intCommand::numCommands=0;intCommand::maxCommands=0;intmain(){inti;std::cout<<"Please enter an integer: ";std::cin>>i;Object*object=newObject(i);Command*commands[3];commands[1]=newCommand(object,&Object::doubleValue);commands[2]=newCommand(object,&Object::increaseByOne);std::cout<<"0.Exit, 1.Double, 2.Increase by one, 3.Undo, 4.Redo: ";std::cin>>i;while(i!=0){if(i==3)Command::undo();elseif(i==4)Command::redo();elseif(i>0&&i<=2)commands[i]->execute();else{std::cout<<"Enter a proper choice: ";std::cin>>i;continue;}std::cout<<" "<<object->getValue()<<" "<<object->getName()<<" "<<object->getDecimal()<<std::endl;std::cout<<"0.Exit, 1.Double, 2.Increase by one, 3.Undo, 4.Redo: ";std::cin>>i;}}

The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Problem

In one place or many places in the application we need to be aware about a system event or an application state change. We'd like to have a standard way of subscribing to listening for system events and a standard way of notifying the interested parties. The notification should be automated after an interested party subscribed to the system event or application state change. There also should be a way to unsubscribe.

Forces

Observers and observables probably should be represented by objects. The observer objects will be notified by the observable objects.

Solution

After subscribing the listening objects will be notified by a way of method call.

The State Pattern allows an object to alter its behavior when its internal state changes. The object will appear as having changed its class.

#include<iostream>#include<string>#include<cstdlib>#include<ctime>#include<memory>enumInput{DUCK_DOWN,STAND_UP,JUMP,DIVE};classFighter;classStandingState;classJumpingState;classDivingState;classFighterState{public:staticstd::shared_ptr<StandingState>standing;staticstd::shared_ptr<DivingState>diving;virtual~FighterState()=default;virtualvoidhandleInput(Fighter&,Input)=0;virtualvoidupdate(Fighter&)=0;};classDuckingState:publicFighterState{private:intchargingTime;staticconstintFullRestTime=5;public:DuckingState():chargingTime(0){}virtualvoidhandleInput(Fighter&,Input)override;virtualvoidupdate(Fighter&)override;};classStandingState:publicFighterState{public:virtualvoidhandleInput(Fighter&,Input)override;virtualvoidupdate(Fighter&)override;};classJumpingState:publicFighterState{private:intjumpingHeight;public:JumpingState(){jumpingHeight=std::rand()%5+1;}virtualvoidhandleInput(Fighter&,Input)override;virtualvoidupdate(Fighter&)override;};classDivingState:publicFighterState{public:virtualvoidhandleInput(Fighter&,Input)override;virtualvoidupdate(Fighter&)override;};std::shared_ptr<StandingState>FighterState::standing(newStandingState);std::shared_ptr<DivingState>FighterState::diving(newDivingState);classFighter{private:std::stringname;std::shared_ptr<FighterState>state;intfatigueLevel=std::rand()%10;public:Fighter(conststd::string&newName):name(newName),state(FighterState::standing){}std::stringgetName()const{returnname;}intgetFatigueLevel()const{returnfatigueLevel;}virtualvoidhandleInput(Inputinput){state->handleInput(*this,input);}// delegate input handling to 'state'.voidchangeState(std::shared_ptr<FighterState>newState){state=newState;updateWithNewState();}voidstandsUp(){std::cout<<getName()<<" stands up."<<std::endl;}voidducksDown(){std::cout<<getName()<<" ducks down."<<std::endl;}voidjumps(){std::cout<<getName()<<" jumps into the air."<<std::endl;}voiddives(){std::cout<<getName()<<" makes a dive attack in the middle of the jump!"<<std::endl;}voidfeelsStrong(){std::cout<<getName()<<" feels strong!"<<std::endl;}voidchangeFatigueLevelBy(intchange){fatigueLevel+=change;std::cout<<"fatigueLevel = "<<fatigueLevel<<std::endl;}private:virtualvoidupdateWithNewState(){state->update(*this);}// delegate updating to 'state'};voidStandingState::handleInput(Fighter&fighter,Inputinput){switch(input){caseSTAND_UP:std::cout<<fighter.getName()<<" remains standing."<<std::endl;return;caseDUCK_DOWN:fighter.changeState(std::shared_ptr<DuckingState>(newDuckingState));returnfighter.ducksDown();caseJUMP:fighter.jumps();returnfighter.changeState(std::shared_ptr<JumpingState>(newJumpingState));default:std::cout<<"One cannot do that while standing. "<<fighter.getName()<<" remains standing by default."<<std::endl;}}voidStandingState::update(Fighter&fighter){if(fighter.getFatigueLevel()>0)fighter.changeFatigueLevelBy(-1);}voidDuckingState::handleInput(Fighter&fighter,Inputinput){switch(input){caseSTAND_UP:fighter.changeState(FighterState::standing);returnfighter.standsUp();caseDUCK_DOWN:std::cout<<fighter.getName()<<" remains in ducking position, ";if(chargingTime<FullRestTime)std::cout<<"recovering in the meantime."<<std::endl;elsestd::cout<<"fully recovered."<<std::endl;returnupdate(fighter);default:std::cout<<"One cannot do that while ducking. "<<fighter.getName()<<" remains in ducking position by default."<<std::endl;update(fighter);}}voidDuckingState::update(Fighter&fighter){chargingTime++;std::cout<<"Charging time = "<<chargingTime<<"."<<std::endl;if(fighter.getFatigueLevel()>0)fighter.changeFatigueLevelBy(-1);if(chargingTime>=FullRestTime&&fighter.getFatigueLevel()<=3)fighter.feelsStrong();}voidJumpingState::handleInput(Fighter&fighter,Inputinput){switch(input){caseDIVE:fighter.changeState(FighterState::diving);returnfighter.dives();default:std::cout<<"One cannot do that in the middle of a jump. "<<fighter.getName()<<" lands from his jump and is now standing again."<<std::endl;fighter.changeState(FighterState::standing);}}voidJumpingState::update(Fighter&fighter){std::cout<<fighter.getName()<<" has jumped "<<jumpingHeight<<" feet into the air."<<std::endl;if(jumpingHeight>=3)fighter.changeFatigueLevelBy(1);}voidDivingState::handleInput(Fighter&fighter,Input){std::cout<<"Regardless of what the user input is, "<<fighter.getName()<<" lands from his dive and is now standing again."<<std::endl;fighter.changeState(FighterState::standing);}voidDivingState::update(Fighter&fighter){fighter.changeFatigueLevelBy(2);}intmain(){std::srand(std::time(nullptr));Fighterrex("Rex the Fighter"),borg("Borg the Fighter");std::cout<<rex.getName()<<" and "<<borg.getName()<<" are currently standing."<<std::endl;intchoice;autochooseAction=[&choice](Fighter&fighter){std::cout<<std::endl<<DUCK_DOWN+1<<") Duck down "<<STAND_UP+1<<") Stand up "<<JUMP+1<<") Jump "<<DIVE+1<<") Dive in the middle of a jump"<<std::endl;std::cout<<"Choice for "<<fighter.getName()<<"? ";std::cin>>choice;constInputinput1=static_cast<Input>(choice-1);fighter.handleInput(input1);};while(true){chooseAction(rex);chooseAction(borg);}}

By defining a skeleton of an algorithm in an operation, deferring some steps to subclasses, the Template Method lets subclasses redefine certain steps of that algorithm without changing the algorithm's structure.

#include<ctime>#include<assert.h>#include<iostream>namespacewikibooks_design_patterns{/** * An abstract class that is common to several games in * which players play against the others, but only one is * playing at a given time. */classGame{public:Game():playersCount(0),movesCount(0),playerWon(-1){srand((unsigned)time(NULL));}/* A template method : */voidplayOneGame(constintplayersCount=0){if(playersCount){this->playersCount=playersCount;}InitializeGame();assert(this->playersCount);intj=0;while(!endOfGame()){makePlay(j);j=(j+1)%this->playersCount;if(!j){++movesCount;}}printWinner();}protected:virtualvoidinitializeGame()=0;virtualvoidmakePlay(intplayer)=0;virtualboolendOfGame()=0;virtualvoidprintWinner()=0;private:voidInitializeGame(){movesCount=0;playerWon=-1;initializeGame();}protected:intplayersCount;intmovesCount;intplayerWon;};//Now we can extend this class in order //to implement actual games:classMonopoly:publicGame{/* Implementation of necessary concrete methods */voidinitializeGame(){// Initialize playersplayersCount=rand()*7/RAND_MAX+2;// Initialize money}voidmakePlay(intplayer){// Process one turn of player// Decide winnerif(movesCount<20)return;constintchances=(movesCount>199)?199:movesCount;constintrandom=MOVES_WIN_CORRECTION*rand()*200/RAND_MAX;if(random<chances)playerWon=player;}boolendOfGame(){// Return true if game is over // according to Monopoly rulesreturn(-1!=playerWon);}voidprintWinner(){assert(playerWon>=0);assert(playerWon<playersCount);// Display who wonstd::cout<<"Monopoly, player "<<playerWon<<" won in "<<movesCount<<" moves."<<std::endl;}private:enum{MOVES_WIN_CORRECTION=20,};};classChess:publicGame{/* Implementation of necessary concrete methods */voidinitializeGame(){// Initialize playersplayersCount=2;// Put the pieces on the board}voidmakePlay(intplayer){assert(player<playersCount);// Process a turn for the player// decide winnerif(movesCount<2)return;constintchances=(movesCount>99)?99:movesCount;constintrandom=MOVES_WIN_CORRECTION*rand()*100/RAND_MAX;//std::cout<<random<<" : "<<chances<<std::endl;if(random<chances)playerWon=player;}boolendOfGame(){// Return true if in Checkmate or // Stalemate has been reachedreturn(-1!=playerWon);}voidprintWinner(){assert(playerWon>=0);assert(playerWon<playersCount);// Display the winning playerstd::cout<<"Player "<<playerWon<<" won in "<<movesCount<<" moves."<<std::endl;}private:enum{MOVES_WIN_CORRECTION=7,};};}intmain(){usingnamespacewikibooks_design_patterns;Game*game=NULL;Chesschess;game=&chess;for(unsignedi=0;i<100;++i)game->playOneGame();Monopolymonopoly;game=&monopoly;for(unsignedi=0;i<100;++i)game->playOneGame();return0;}

The Visitor Pattern will represent an operation to be performed on the elements of an object structure by letting you define a new operation without changing the classes of the elements on which it operates.

#include<string>#include<iostream>#include<vector>usingnamespacestd;classWheel;classEngine;classBody;classCar;// interface to all car 'parts'structCarElementVisitor{virtualvoidvisit(Wheel&wheel)const=0;virtualvoidvisit(Engine&engine)const=0;virtualvoidvisit(Body&body)const=0;virtualvoidvisitCar(Car&car)const=0;virtual~CarElementVisitor(){};};// interface to one partstructCarElement{virtualvoidaccept(constCarElementVisitor&visitor)=0;virtual~CarElement(){}};// wheel element, there are four wheels with unique namesclassWheel:publicCarElement{public:explicitWheel(conststring&name):name_(name){}conststring&getName()const{returnname_;}voidaccept(constCarElementVisitor&visitor){visitor.visit(*this);}private:stringname_;};// engineclassEngine:publicCarElement{public:voidaccept(constCarElementVisitor&visitor){visitor.visit(*this);}};// bodyclassBody:publicCarElement{public:voidaccept(constCarElementVisitor&visitor){visitor.visit(*this);}};// car, all car elements(parts) togetherclassCar{public:vector<CarElement*>&getElements(){returnelements_;}Car(){// assume that neither push_back nor Wheel(const string&) may throwelements_.push_back(newWheel("front left"));elements_.push_back(newWheel("front right"));elements_.push_back(newWheel("back left"));elements_.push_back(newWheel("back right"));elements_.push_back(newBody());elements_.push_back(newEngine());}~Car(){for(vector<CarElement*>::iteratorit=elements_.begin();it!=elements_.end();++it){delete*it;}}private:vector<CarElement*>elements_;};// PrintVisitor and DoVisitor show by using a different implementation the Car class is unchanged// even though the algorithm is different in PrintVisitor and DoVisitor.classCarElementPrintVisitor:publicCarElementVisitor{public:voidvisit(Wheel&wheel)const{cout<<"Visiting "<<wheel.getName()<<" wheel"<<endl;}voidvisit(Engine&engine)const{cout<<"Visiting engine"<<endl;}voidvisit(Body&body)const{cout<<"Visiting body"<<endl;}voidvisitCar(Car&car)const{cout<<endl<<"Visiting car"<<endl;vector<CarElement*>&elems=car.getElements();for(vector<CarElement*>::iteratorit=elems.begin();it!=elems.end();++it){(*it)->accept(*this);// this issues the callback i.e. to this from the element }cout<<"Visited car"<<endl;}};classCarElementDoVisitor:publicCarElementVisitor{public:// these are specific implementations added to the original object without modifying the original structvoidvisit(Wheel&wheel)const{cout<<"Kicking my "<<wheel.getName()<<" wheel"<<endl;}voidvisit(Engine&engine)const{cout<<"Starting my engine"<<endl;}voidvisit(Body&body)const{cout<<"Moving my body"<<endl;}voidvisitCar(Car&car)const{cout<<endl<<"Starting my car"<<endl;vector<CarElement*>&elems=car.getElements();for(vector<CarElement*>::iteratorit=elems.begin();it!=elems.end();++it){(*it)->accept(*this);// this issues the callback i.e. to this from the element }cout<<"Stopped car"<<endl;}};intmain(){Carcar;CarElementPrintVisitorprintVisitor;CarElementDoVisitordoVisitor;printVisitor.visitCar(car);doVisitor.visitCar(car);return0;}

A pattern often used by applications that need the ability to maintain multiple views of the same data. The model-view-controller pattern was until recently[citation needed] a very common pattern especially for graphic user interlace programming, it splits the code in 3 pieces. The model, the view, and the controller.

The Model is the actual data representation (for example, Array vs Linked List) or other objects representing a database. The View is an interface to reading the model or a fat client GUI. The Controller provides the interface of changing or modifying the data, and then selecting the "Next Best View" (NBV).

Newcomers will probably see this "MVC" model as wasteful, mainly because you are working with many extra objects at runtime, when it seems like one giant object will do. But the secret to the MVC pattern is not writing the code, but in maintaining it, and allowing people to modify the code without changing much else. Also, keep in mind, that different developers have different strengths and weaknesses, so team building around MVC is easier. Imagine a View Team that is responsible for great views, a Model Team that knows a lot about data, and a Controller Team that see the big picture of application flow, handing requests, working with the model, and selecting the most appropriate next view for that client.

To do:
Erm, someone please come up with a better example than the following... I can not think of any

Perhaps a banking program for customer access to their accounts: A web UI on a traditional browser vs mobile app? And then handling checking/savings accounts vs loan vs line-of-credit accounts? fwiw

For example: A naive central database can be organized using only a "model", for example, a straight array. However, later on, it may be more applicable to use a linked list. All array accesses will have to be remade into their respective Linked List form (for example, you would change myarray[5] into mylist.at(5) or whatever is equivalent in the language you use).

Well, if we followed the MVC pattern, the central database would be accessed using some sort of a function, for example, myarray.at(5). If we change the model from an array to a linked list, all we have to do is change the view with the model, and the whole program is changed. Keep the interface the same but change the underpinnings of it. This would allow us to make optimizations more freely and quickly than before.

One of the great advantages of the Model-View-Controller Pattern is obviously the ability to reuse the application's logic (which is implemented in the model) when implementing a different view. A good example is found in web development, where a common task is to implement an external API inside of an existing piece of software. If the MVC pattern has cleanly been followed, this only requires modification to the controller, which can have the ability to render different types of views dependent on the content type requested by the user agent.