C++ Programming: Code design and behavioral patterns

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.

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.