Wednesday, 25 August 2010

An example of replacing part of strings

Taking a bit of break from the Design Patterns this week. We look at a simple example of replacing part of the strings. For example you may have a program which prints out some customised letter. You may want to replace the default name with the name of a person that can be input on command line.



Example as follows:





//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>
#include<string>

using namespace
std;

int
main()
{

string s1 = "Hello is that Tom? Are you ok Tom? Take Care tom!";
string s2 = "Tom";
string s3 = "William";

cout << "s1 = " << s1 << endl;

//Find s2 and replace by s3
bool flag = true;
while
(flag)
{

size_t found = s1.find(s2);
if
(found != string::npos)
{

s1.replace(found, s2.length(), s3);
}

else

{

flag = false;
}
}


cout << "s1 = " << s1 << endl;

return
0;
}






The output is as follows:







Friday, 20 August 2010

C++ example for Singleton Design Pattern


The Singleton Design Pattern which is widely used ensures that there is a single instance of the object and it also provides a global point of access to it.
I have covered couple of examples on Singletons in past and you are welcome to refer to them as an example for this design pattern. The simple example is here and a more involved one is here.
To learn more about Singletons see:

Tuesday, 17 August 2010

C++ example for Prototype Design Pattern

The Protoype pattern is used when creating an instance of a class is very time-consuming or complex in some way. Then, rather than creating more instances, you make copies of the original instance, modifying them as appropriate.


Prototypes can also be used whenever you need classes that differ only in the type of processing they offer, for example in parsing of strings representing numbers in different radixes. This design pattern is not used very frequently.

The following is an example of Prototype Design Pattern:

//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Prototype is part of Creational Patterns
//Creational Patterns deal with initializing and configuring classes and objects
//Prototype creates a fully initialized instance to be copied or cloned

//We will take an example of creating Colour class.
//There are three parts to colour - Red, Green and Blue
//Simple colours like Red only contain the red component
//Complex colours like Angry and Peace contains all three components

#include <iostream>
#include <string>
#include <iomanip>
#include <map>

using namespace
std;

//The abstract 'Protoype' class
class ColourPrototype
{

public
:
virtual
ColourPrototype* Clone(void) = 0;
};


//The 'ConcretePrototype' class
class Colour : public ColourPrototype
{

public
:
Colour(int red, int green, int blue)
{

red_ = red, green_ = green, blue_ = blue;
}

ColourPrototype* Clone(void)
{

cout << "Cloning colour RGB: " << setw(3) << red_ << ", " << setw(3) << green_ <<", " << setw(3) << blue_ <<endl;
ColourPrototype* colourPrototype = new Colour(red_, green_, blue_);
return
colourPrototype;
}

void
SetRed(int red)
{

red_ = red;
}

void
SetGreen(int green)
{

green_ = green;
}

void
SetBlue(int blue)
{

blue_ = blue;
}

int
GetRed(void)
{

return
red_;
}

int
GetGreen(void)
{

return
green_;
}

int
GetBlue(void)
{

return
blue_;
}


private
:
Colour(); //default constructor not allowed
int red_, green_, blue_;
};


//Prototype manager
class ColourManager
{

public
:
virtual
~ColourManager()
{

while
(!coloursMap_.empty())
{

map<string, ColourPrototype*>::iterator it = coloursMap_.begin();
delete
it->second;
coloursMap_.erase(it);
}
}

void
AddColour(const string& colour, ColourPrototype* prototype)
{

coloursMap_[colour] = prototype;
}

ColourPrototype* GetColour(const string& colour)
{

map<string, ColourPrototype*>::const_iterator it = coloursMap_.find(colour);
if
(it != coloursMap_.end())
return
it->second;
return
NULL;
}

void
PrintColours(void)
{

cout << "\nAvailable Colours and their values " << endl;
map<string, ColourPrototype*>::const_iterator it = coloursMap_.begin();
while
(it != coloursMap_.end())
{

cout << setw(20) << it->first << " : ";
cout << setw(3) << dynamic_cast<Colour*>(it->second)->GetRed() << ", ";
cout << setw(3) << dynamic_cast<Colour*>(it->second)->GetGreen() << ", ";
cout << setw(3) << dynamic_cast<Colour*>(it->second)->GetBlue() << endl;
++
it;
}
}

private
:
map<string, ColourPrototype*> coloursMap_;
};



//The Main method
int main()
{

ColourManager* colourManager = new ColourManager();

//Add simple colours
colourManager->AddColour("Red", new Colour(255, 0, 0));
colourManager->AddColour("Green", new Colour(0, 255, 0));
colourManager->AddColour("Blue", new Colour(0, 0, 255));

//Add complex colours
colourManager->AddColour("Angry", new Colour(255, 54, 0));
colourManager->AddColour("Peace", new Colour(128, 211, 128));
colourManager->AddColour("Flame", new Colour(211, 34, 20));

//Clone existing colours, modify and add them to the manager
ColourPrototype* colour1 = (colourManager->GetColour("Red"))->Clone();
(
dynamic_cast<Colour*>(colour1))->SetRed(200);
colourManager->AddColour("Light Red", colour1);

ColourPrototype* colour2 = (colourManager->GetColour("Peace"))->Clone();
(
dynamic_cast<Colour*>(colour2))->SetRed(150);
(
dynamic_cast<Colour*>(colour2))->SetBlue(150);
colourManager->AddColour("Extreme Peace", colour2);

ColourPrototype* colour3 = (colourManager->GetColour("Flame"))->Clone();
(
dynamic_cast<Colour*>(colour3))->SetRed(255);
colourManager->AddColour("Hot Flame", colour3);

colourManager->PrintColours();

//clean the memory
delete colourManager;

return
0;
}


The output is as follows:



Other good example of Prototype is available here and here.

Wednesday, 11 August 2010

C++ example for Factory Method Design Pattern

The Factory Method Design Pattern defines an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. This design pattern is used very frequently in practice.

The following is an example of Factory Method Design Pattern:

//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Factory Method is part of Creational Patterns
//Creational Patterns deal with initializing and configuring classes and objects
//Factory Method creates an instance of several derived classes

//We will take an example of creating Pages for Document.
//There are 2 types of Document: Resume and Report
//Different Document can instantiate different Pages based on their requirements

#include <iostream>
#include <string>
#include <list>

using namespace
std;

//Create the abstract 'Product' class
class Page
{

public
:
virtual
string GetPageName(void) = 0;
};


//'ConcreteProduct'#1 class
class SkillsPage : public Page
{

public
:
string GetPageName(void)
{

return
"SkillsPage";
}
};


//'ConcreteProduct'#2 class
class EducationPage : public Page
{

public
:
string GetPageName(void)
{

return
"EducationPage";
}
};


//'ConcreteProduct'#3 class
class ExperiencePage : public Page
{

public
:
string GetPageName(void)
{

return
"ExperiencePage";
}
};


//'ConcreteProduct'#4 class
class IntroductionPage : public Page
{

public
:
string GetPageName(void)
{

return
"IntroductionPage";
}
};


//'ConcreteProduct'#5 class
class ResultsPage : public Page
{

public
:
string GetPageName(void)
{

return
"ResultsPage";
}
};


//'ConcreteProduct'#6 class
class ConclusionPage : public Page
{

public
:
string GetPageName(void)
{

return
"ConclusionPage";
}
};


//'ConcreteProduct'#7 class
class SummaryPage : public Page
{

public
:
string GetPageName(void)
{

return
"SummaryPage";
}
};


//'ConcreteProduct'#8 class
class BibliographyPage : public Page
{

public
:
string GetPageName(void)
{

return
"BibliographyPage";
}
};


//Create the abstract 'Creator' class
class Document
{

public
:
//constructor
Document()
{

//CreatePages(); - Cannot be called directly in constructor because its virtual
//Should be called in the Derived class
}
void
AddPages(Page* page)
{

pages_.push_back(page);
}

const
list<Page*>& GetPages(void)
{

return
pages_;
}

//Factory Method
virtual void CreatePages(void) = 0;
private
:
list<Page*> pages_;
};


//Create the 'ConcreteCreator' # 1 class
class Resume : public Document
{

public
:
Resume()
{

CreatePages();
}

void
CreatePages(void)
{

AddPages(new SkillsPage());
AddPages(new EducationPage());
AddPages(new ExperiencePage());
}
};


//Create the 'ConcreteCreator' # 2 class
class Report : public Document
{

public
:
Report()
{

CreatePages();
}

void
CreatePages(void)
{

AddPages(new SummaryPage());
AddPages(new IntroductionPage());
AddPages(new ResultsPage());
AddPages(new ConclusionPage());
AddPages(new BibliographyPage());
}
};



//The Main method
int main()
{

//Create two types of documents - constructors call Factory method
Document* doc1 = new Resume();
Document* doc2 = new Report();

//Get and print the pages of the first document
list<Page*>& doc1Pages = const_cast<list<Page*>&> (doc1->GetPages());
cout << "\nResume Pages -------------" << endl;
for
(list<Page*>::iterator it = doc1Pages.begin(); it != doc1Pages.end(); it++)
{

cout << "\t" << (*it)->GetPageName() << endl;
}


//Get and print the pages of the second document
list<Page*>& doc2Pages = const_cast<list<Page*>&> (doc2->GetPages());
cout << "\nReport Pages -------------" << endl;
for
(list<Page*>::iterator it = doc2Pages.begin(); it != doc2Pages.end(); it++)
{

cout << "\t" << (*it)->GetPageName() << endl;
}


return
0;
}


The output is as follows:

Wednesday, 4 August 2010

C++ example for Builder Design Pattern

The Builder Design Pattern separates the construction of a complex object from its representation so that the same construction process can create different representations. This design pattern is not used very often in practice.

The following is an example of Builder Design Pattern:


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Builder is part of Creational Patterns
//Creational Patterns deal with initializing and configuring classes and objects
//Builder Separates object construction from its representation

//We will take an example of creating Vehicles using Vehicle class.
//The VehicleBuilder is the abstract interface for creating the parts of Vehicle
//Different ConcreteBuilder classes are used to construct the final Product
//The Shop class is the Director that defines the sequence of construction
//The final product, Vehicle class shows the different type of Vehicle
//constructed and consists of different parts that can be assembles in final result

#include <iostream>
#include <string>
#include <map>

using namespace
std;

//The 'Product' class
class Vehicle
{

public
:
Vehicle(const string& vehicleType) : vehicleType_(vehicleType)
{
}


void
SetPart(const string& partName, const string& partValue)
{

parts_[partName] = partValue;
}


const
string& GetpartValue(const string& partName)
{

map<string, string>::const_iterator it;
it = parts_.find(partName);
if
(it != parts_.end())
return
it->second;
else

{

parts_[partName] = "Not found";
return
parts_[partName];
}
}


void
const Show(void)
{

cout << "\n---------------------------" << endl;
cout << "Vehicle Type : " << vehicleType_ << endl;
cout << "Frame : " << parts_["frame"] << endl;
cout << "Engine : " << parts_["engine"] << endl;
cout << "#Wheels : " << parts_["wheels"] << endl;
cout << "#Doors : " << parts_["doors"] << endl;
}


private
:
Vehicle(); //Default constructor is private so not allowed to be used
string vehicleType_;
map<string, string> parts_;
};


//Create an abstract 'Builder' class
class VehicleBuilder
{

public
:
//Default constructor wont work as pointer needs init
VehicleBuilder()
{

vehicle = NULL;
}

//Destructor made virtual
virtual ~VehicleBuilder()
{

if
(vehicle)
{

delete
vehicle;
vehicle = NULL;
}
}

const
Vehicle& getVehicle(void)
{

return
*vehicle;
}

virtual
void BuildFrame() = 0;
virtual
void BuildEngine() = 0;
virtual
void BuildWheels() = 0;
virtual
void BuildDoors() = 0;
protected
:
Vehicle* vehicle;
};


//The Concrete 'Builder' #1 class
class MotorCycleBuilder : public VehicleBuilder
{

public
:
MotorCycleBuilder()
{

vehicle = new Vehicle("MotorCycle");
}

void
BuildFrame()
{

vehicle->SetPart("frame", "MotorCycle Frame");
}

virtual
void BuildEngine()
{

vehicle->SetPart("engine", "500 cc");
}

virtual
void BuildWheels()
{

vehicle->SetPart("wheels", "2");
}

virtual
void BuildDoors()
{

vehicle->SetPart("doors", "0");
}
};


//The Concrete 'Builder' #2 class
class CarBuilder : public VehicleBuilder
{

public
:
CarBuilder()
{

vehicle = new Vehicle("Car");
}

void
BuildFrame()
{

vehicle->SetPart("frame", "Car Frame");
}

virtual
void BuildEngine()
{

vehicle->SetPart("engine", "2500 cc");
}

virtual
void BuildWheels()
{

vehicle->SetPart("wheels", "4");
}

virtual
void BuildDoors()
{

vehicle->SetPart("doors", "4");
}
};


//The Concrete 'Builder' #3 class
class ScooterBuilder : public VehicleBuilder
{

public
:
ScooterBuilder()
{

vehicle = new Vehicle("Scooter");
}

void
BuildFrame()
{

vehicle->SetPart("frame", "Scooter Frame");
}

virtual
void BuildEngine()
{

vehicle->SetPart("engine", "50 cc");
}

virtual
void BuildWheels()
{

vehicle->SetPart("wheels", "2");
}

virtual
void BuildDoors()
{

vehicle->SetPart("doors", "0");
}
};


//The 'Director' class
class Shop
{

public
:
void
Construct(VehicleBuilder* vehicleBuilder)
{

vehicleBuilder->BuildFrame();
vehicleBuilder->BuildEngine();
vehicleBuilder->BuildWheels();
vehicleBuilder->BuildDoors();
}
};


int
main()
{

VehicleBuilder *builder = NULL;

Shop shop; //New Instance of class created locally.

//Construct vehicle 1 and destroy instance when done
builder = new ScooterBuilder();
shop.Construct(builder);
(
const_cast<Vehicle&>(builder->getVehicle())).Show();
delete
builder;

//Construct vehicle 2 and destroy instance when done
builder = new CarBuilder();
shop.Construct(builder);
(
const_cast<Vehicle&>(builder->getVehicle())).Show();
delete
builder;

//Construct vehicle 3 and destroy instance when done
builder = new MotorCycleBuilder();
shop.Construct(builder);
(
const_cast<Vehicle&>(builder->getVehicle())).Show();
delete
builder;

return
0;
}


The output is as follows: