Wednesday, 29 September 2010

C++ example for Facade Design Pattern



Frequently, as your programs evolve and develop, they grow in complexity. In fact, for all the excitement about using design patterns, these patterns sometimes generate so many classes that it is difficult to understand the program’s flow. Furthermore, there may be a number of complicated subsystems, each of which has its own complex interface.

The Façade pattern allows you to simplify this complexity by providing a simplified interface to these subsystems. This simplification may in some cases reduce the flexibility of the underlying classes, but usually provides all the function needed for all but the most sophisticated users. These users can still, of course, access the underlying classes and methods.

Facade takes a “riddle wrapped in an enigma shrouded in mystery”, and interjects a wrapper that tames the amorphous and inscrutable mass of software.

The frequency of use for Facade is very high.

C++ example as follows:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Façade is part of Structural Patterns
//Structural Patterns deal with decoupling the interface and implementation of classes and objects
//A Facade is single class that represents an entire subsystem

//The example we consider here is a case of a customer applying for mortgage
//The bank has to go through various checks to see if Mortgage can be approved for the customer
//The facade class goes through all these checks and returns if the morgage is approved

#include<iostream>
#include<string>

using namespace
std;

// Customer class
class Customer
{

public
:
Customer (const string& name) : name_(name){}
const
string& Name(void)
{

return
name_;
}

private
:
Customer(); //not allowed
string name_;
};


// The 'Subsystem ClassA' class
class Bank
{

public
:
bool
HasSufficientSavings(Customer c, int amount)
{

cout << "Check bank for " <<c.Name()<<endl;
return
true;
}
};


// The 'Subsystem ClassB' class
class Credit
{

public
:
bool
HasGoodCredit(Customer c, int amount)
{

cout << "Check credit for " <<c.Name()<<endl;
return
true;
}
};


// The 'Subsystem ClassC' class
class Loan
{

public
:
bool
HasGoodCredit(Customer c, int amount)
{

cout << "Check loans for " <<c.Name()<<endl;
return
true;
}
};


// The 'Facade' class
class Mortgage
{

public
:
bool
IsEligible(Customer cust, int amount)
{

cout << cust.Name() << " applies for a loan for $" << amount <<endl;
bool
eligible = true;

eligible = bank_.HasSufficientSavings(cust, amount);

if
(eligible)
eligible = loan_.HasGoodCredit(cust, amount);

if
(eligible)
eligible = credit_.HasGoodCredit(cust, amount);

return
eligible;
}


private
:
Bank bank_;
Loan loan_;
Credit credit_;
};


//The Main method
int main()
{

Mortgage mortgage;
Customer customer("Brad Pitt");

bool
eligible = mortgage.IsEligible(customer, 1500000);

cout << "\n" << customer.Name() << " has been " << (eligible ? "Approved" : "Rejected") << endl;

return
0;
}



The output is as follows:


More on Facade:

http://sourcemaking.com/design_patterns/facade

http://www.patterndepot.com/put/8/facade.pdf

http://sourcemaking.com/design_patterns/facade

Wednesday, 22 September 2010

C++ example for Decorator Design Pattern


The Decorator Pattern is used for adding additional functionality to a particular object as opposed to a class of objects. It is easy to add functionality to an entire class of objects by subclassing an object, but it is impossible to extend a single object this way. With the Decorator Pattern, you can add functionality to a single object and leave others like it unmodified.

A Decorator, also known as a Wrapper, is an object that has an interface identical to an object that it contains. Any calls that the decorator gets, it relays to the object that it contains, and adds its own functionality along the way, either before or after the call. This gives you a lot of flexibility, since you can change what the decorator does at runtime, as opposed to having the change be static and determined at compile time by subclassing. Since a Decorator complies with the interface that the object that it contains, the Decorator is indistinguishable from the object that it contains. That is, a Decorator is a concrete instance of the abstract class, and thus is indistinguishable from any other concrete instance, including other decorators. This can be used to great advantage, as you can recursively nest decorators without any other objects being able to tell the difference, allowing a near infinite amount of customization.

Decorators add the ability to dynamically alter the behavior of an object because a decorator can be added or removed from an object without the client realizing that anything changed. It is a good idea to use a Decorator in a situation where you want to change the behaviour of an object repeatedly (by adding and subtracting functionality) during runtime.

The dynamic behavior modification capability also means that decorators are useful for adapting objects to new situations without re-writing the original object's code.

The frequency for use of Decorator is medium. The following is example code for this pattern:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Decorator is part of Structural Patterns
//Structural Patterns deal with decoupling the interface and implementation of classes and objects
//The Decorator pattern provides us with a way to modify the behavior of individual objects without
// having to create a new derived class.

//The example here shows a Library that contains information about the books
//After the class was created, it was decided to have a borrowable functionality added

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

using namespace
std;

// The 'Component' abstract class
class LibraryItem
{

public
:
void
SetNumCopies(int value)
{

numCopies_ = value;
}

int
GetNumCopies(void)
{

return
numCopies_;
}

virtual
void Display(void)=0;
private
:
int
numCopies_;
};


// The 'ConcreteComponent' class#1
class Book : public LibraryItem
{

public
:
Book(string author, string title, int numCopies) : author_(author), title_(title)
{

SetNumCopies(numCopies);
}

void
Display(void)
{

cout<<"\nBook ------ "<<endl;
cout<<" Author : "<<author_<<endl;
cout<<" Title : "<<title_<<endl;
cout<<" # Copies : "<<GetNumCopies()<<endl;
}

private
:
Book(); //Default not allowed
string author_;
string title_;
};


// The 'ConcreteComponent' class#2
class Video : public LibraryItem
{

public
:
Video(string director, string title, int playTime, int numCopies) : director_(director), title_(title), playTime_(playTime)
{

SetNumCopies(numCopies);
}

void
Display(void)
{

cout<<"\nVideo ------ "<<endl;
cout<<" Director : "<<director_<<endl;
cout<<" Title : "<<title_<<endl;
cout<<" Play Time : "<<playTime_<<" mins"<<endl;
cout<<" # Copies : "<<GetNumCopies()<<endl;
}

private
:
Video(); //Default not allowed
string director_;
string title_;
int
playTime_;
};


// The 'Decorator' abstract class
class Decorator : public LibraryItem
{

public
:
Decorator(LibraryItem* libraryItem) : libraryItem_(libraryItem) {}
void
Display(void)
{

libraryItem_->Display();
}

int
GetNumCopies(void)
{

return
libraryItem_->GetNumCopies();
}

protected
:
LibraryItem* libraryItem_;
private
:
Decorator(); //not allowed
};

// The 'ConcreteDecorator' class
class Borrowable : public Decorator
{

public
:
Borrowable(LibraryItem* libraryItem) : Decorator(libraryItem) {}
void
BorrowItem(string name)
{

borrowers_.push_back(name);
}

void
ReturnItem(string name)
{

list<string>::iterator it = borrowers_.begin();
while
(it != borrowers_.end())
{

if
(*it == name)
{

borrowers_.erase(it);
break
;
}
++
it;
}
}

void
Display()
{

Decorator::Display();
int
size = (int)borrowers_.size();
cout<<" # Available Copies : "<<(Decorator::GetNumCopies() - size)<<endl;
list<string>::iterator it = borrowers_.begin();
while
(it != borrowers_.end())
{

cout<<" borrower: "<<*it<<endl;
++
it;
}
}

protected
:
list<string> borrowers_;
};


//The Main method
int main()
{

Book book("Erik Dahlman","3G evolution",6);
book.Display();

Video video("Peter Jackson", "The Lord of the Rings", 683, 24);
video.Display();

cout<<"Making video borrowable"<<endl;
Borrowable borrowvideo(&video);
borrowvideo.BorrowItem("Bill Gates");
borrowvideo.BorrowItem("Steve Jobs");
borrowvideo.Display();

return
0;
}



The output is as follows:


For more information see:

http://www.dofactory.com/Patterns/PatternDecorator.aspx

http://sourcemaking.com/design_patterns/decorator

http://www.patterndepot.com/put/8/Decorator.pdf

http://www.exciton.cs.rice.edu/javaresources/designpatterns/decoratorpattern.htm

Wednesday, 15 September 2010

C++ example for Composite Design Pattern


Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly. The frequency of use of this is medium high.

The Intent of the 'Composite Pattern' is:
  • Compose objects into tree structures to represent whole-part hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
  • Recursive composition
  • “Directories contain entries, each of which could be a directory.”
  • 1-to-many “has a” up the “is a” hierarchy
C++ example as follows:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Composite is part of Structural Patterns
//Structural Patterns deal with decoupling the interface and implementation of classes and objects
//Composite pattern forms a tree structure of simple and composite objects

//The example here

#include<iostream>
#include<string>
#include<vector>

using namespace
std;

//The 'Component' Treenode
class DrawingElement
{

public
:
DrawingElement(string name) : name_(name) {};
virtual
void Add(DrawingElement* d) = 0;
virtual
void Remove(DrawingElement* d) = 0;
virtual
void Display(int indent) = 0;
virtual
~DrawingElement() {};
protected
:
string name_;
private
:
DrawingElement(); //not allowed
};

//The 'Leaf' class
class PrimitiveElement : public DrawingElement
{

public
:
PrimitiveElement(string name) : DrawingElement(name){};
void
Add(DrawingElement* d)
{

cout<<"Cannot add to a PrimitiveElement"<<endl;
}

void
Remove(DrawingElement* d)
{

cout<<"Cannot remove from a PrimitiveElement"<<endl;
}

void
Display(int indent)
{

string newStr(indent, '-');
cout << newStr << " " << name_ <<endl;
}

virtual
~PrimitiveElement(){};
private
:
PrimitiveElement(); //not allowed
};

//The 'Composite' class
class CompositeElement : public DrawingElement
{

public
:
CompositeElement(string name) : DrawingElement(name) {};
void
Add(DrawingElement* d)
{

elements_.push_back(d);
}

void
Remove(DrawingElement* d)
{

vector<DrawingElement*>::iterator it = elements_.begin();
while
(it != elements_.end())
{

if
(*it == d)
{

delete
d;
elements_.erase(it);
break
;
}
++
it;
}
}

void
Display(int indent)
{

string newStr(indent, '-');
cout << newStr << "+ " << name_ <<endl;
vector<DrawingElement*>::iterator it = elements_.begin();
while
(it != elements_.end())
{
(*
it)->Display(indent + 2);
++
it;
}
}

virtual
~CompositeElement()
{

while
(!elements_.empty())
{

vector<DrawingElement*>::iterator it = elements_.begin();
delete
*it;
elements_.erase(it);
}
}

private
:
CompositeElement(); //not allowed
vector<DrawingElement*> elements_;

};


//The Main method
int main()
{

//Create a Tree Structure
CompositeElement* root = new CompositeElement("Picture");
root->Add(new PrimitiveElement("Red Line"));
root->Add(new PrimitiveElement("Blue Circle"));
root->Add(new PrimitiveElement("Green Box"));

//Create a Branch
CompositeElement* comp = new CompositeElement("Two Circles");
comp->Add(new PrimitiveElement("Black Circle"));
comp->Add(new PrimitiveElement("White Circle"));
root->Add(comp);

//Add and remove a primitive elements
PrimitiveElement* pe1 = new PrimitiveElement("Yellow Line");
root->Add(pe1);
PrimitiveElement* pe2 = new PrimitiveElement("Orange Triangle");
root->Add(pe2);
root->Remove(pe1);

//Recursively display nodes
root->Display(1);

//delete the allocated memory
delete root;

return
0;
}



The output is as follows:
For more information see:

Wednesday, 8 September 2010

C++ example for Bridge Design Pattern

The Bridge pattern decouples an abstraction from its implementation, so that the two can vary independently. A household switch controlling lights, ceiling fans, etc. is an example of the Bridge. The purpose of the switch is to turn a device on or off. The actual switch can be implemented as a pull chain, simple two position switch, or a variety of dimmer switches.


Differences between Bridge, Adapter and other patterns
  • Adapter makes things work after they’re designed; Bridge makes them work before they are.
  • Bridge is designed up-front to let the abstraction and the implementation vary independently. Adapter is retrofitted to make unrelated classes work together.
  • State, Strategy, Bridge (and to some degree Adapter) have similar solution structures. They all share elements of the “handle/body” idiom. They differ in intent - that is, they solve different problems.
  • The structure of State and Bridge are identical (except that Bridge admits hierarchies of envelope classes, whereas State allows only one). The two patterns use the same structure to solve different problems: State allows an object’s behavior to change along with its state, while Bridge’s intent is to decouple an abstraction from its implementation so that the two can vary independently.
  • If interface classes delegate the creation of their implementation classes (instead of creating/coupling themselves directly), then the design usually uses the Abstract Factory pattern to create the implementation objects.
The frequency of use of Bridge is medium and the UML diagram is as follows:



Example of Bridge as follows:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Bridge is part of Structural Patterns
//Structural Patterns deal with decoupling the interface and implementation of classes and objects
//Bridge separates an object's interface from its implementation


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

using namespace
std;

//The 'Implementor' abstract class
class DataObject
{

public
:
virtual
void NextRecord()=0;
virtual
void PriorRecord()=0;
virtual
void AddRecord(string name)=0;
virtual
void DeleteRecord(string name)=0;
virtual
void ShowRecord()=0;
virtual
void ShowAllRecords()=0;
};


//The 'ConcreteImplementor' class
class CustomersData : public DataObject
{

public
:
CustomersData()
{

current_ = 0;
}

void
NextRecord()
{

if
(current_ < (int)(customers_.size() - 1))
current_++;
}

void
PriorRecord()
{

if
(current_ > 0)
current_--;
}

void
AddRecord(string name)
{

customers_.push_back(name);
}

void
DeleteRecord(string name)
{

list<string>::iterator it = customers_.begin();
while
(it != customers_.end())
{

if
(*it == name)
{

customers_.erase(it);
break
;
}
++
it;
}
}

void
ShowRecord()
{

list<string>::iterator it = customers_.begin();
for
(int i = 0; i < current_; i++, ++it);
cout<<*it<<endl;
}

void
ShowAllRecords()
{

list<string>::iterator it = customers_.begin();
while
(it != customers_.end())
{

cout<<*it<<endl;
++
it;
}
}

private
:
int
current_;
list<string> customers_;
};


//The 'Abstraction' class
class CustomersBase
{

public
:
CustomersBase(string group):group_(group){};
void
SetDataObject(DataObject* value)
{

dataObject_ = value;
}

DataObject* GetDataObject(void)
{

return
dataObject_;
}

virtual
void Next()
{

dataObject_->NextRecord();
}

virtual
void Prior()
{

dataObject_->PriorRecord();
}

virtual
void Add(string customer)
{

dataObject_->AddRecord(customer);
}

virtual
void Delete(string customer)
{

dataObject_->DeleteRecord(customer);
}

virtual
void Show()
{

dataObject_->ShowRecord();
}

virtual
void ShowAll()
{

cout<<"Customer Group : "<<group_<<endl;
dataObject_->ShowAllRecords();
}

protected
:
string group_;
private
:
DataObject* dataObject_;
};


//The 'RefinedAbstraction' class
class Customers : public CustomersBase
{

public
:
Customers(string group) : CustomersBase(group) {};
//overriding
void ShowAll()
{

cout<<"\n------------------------------------"<<endl;
CustomersBase::ShowAll();
cout<<"------------------------------------"<<endl;
}
};


//Main
int main()
{

//Create RefinedAbstraction
Customers* customers = new Customers("London");

//Set ConcreteImplementor
CustomersData* customersData = new CustomersData();
DataObject* dataObject = customersData;

customersData->AddRecord("Tesco");
customersData->AddRecord("Sainsburys");
customersData->AddRecord("Asda");
customersData->AddRecord("Morrisons");
customersData->AddRecord("Lidl");
customersData->AddRecord("Co-op");

customers->SetDataObject(dataObject);

//Exercise the bridge
customers->Show();
customers->Next();
customers->Show();
customers->Next();
customers->Show();
customers->Add("M&S");

customers->ShowAll();


return
0;
}



The Output is as follows:



For more information see:
http://www.dofactory.com/Patterns/PatternBridge.aspx
http://sourcemaking.com/design_patterns/bridge
http://www.vincehuston.org/dp/bridge.html

Wednesday, 1 September 2010

C++ example for Adapter Design Pattern

The Adapter pattern is used to convert the programming interface of one class into that of another. We use adapters whenever we want unrelated classes to work together in a single program. The concept of an adapter is thus pretty simple; we write a class that has the desired interface and then make it communicate with the class that has a different interface.

There are two ways to do this: by inheritance, and by object composition. In the first case, we derive a new class from the nonconforming one and add the methods we need to make the new derived class match the desired interface. The other way is to include the original class inside the new one and create the methods to translate calls within the new class. These two approaches are termed as class adapters and object adapters respectively.

The frequency of usage of adapter pattern is medium high.

Example of Adapter pattern as follows:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Adapter is part of Structural Patterns
//Structural Patterns deal with decoupling the interface and implementation of classes and objects
//Adapter pattern is used to convert the programming interface of one class into that of another.

//We Take an example where chemical compound objects accesses the databank
//through an Adapter Interface

#include<iostream>
#include<string>

using namespace
std;

//The 'Target' class
class Compound
{

public
:
Compound(string chemical):chemical_(chemical){}
virtual
~Compound() {};
void
Display()
{

cout << "\nCompound: " << chemical_ << "----------------" << endl;
}

protected
:
string chemical_;
float
boilingPoint_;
float
meltingPoint_;
double
molecularWeight_;
string molecularFormula_;
private
:
Compound(); //disallow default constructor
};

//The 'Adaptee' class
class ChemicalDatabank
{

public
:
virtual
~ChemicalDatabank() {};
//The databank 'legacy API'
float GetCriticalPoint(string compound, string point)
{

string lowerCompound = toLowerString(compound);
//Melting Point
if (point == "M")
{

if
(_stricmp(lowerCompound.c_str(), "water") == 0)
return
0.0;
else if
(_stricmp(lowerCompound.c_str(), "benzene") == 0)
return
5.5;
else if
(_stricmp(lowerCompound.c_str(), "ethanol") == 0)
return
(float) -114.1;
else
return
0.0;
}

//Boiling point
else
{

if
(_stricmp(lowerCompound.c_str(), "water") == 0)
return
(float) 100.0;
else if
(_stricmp(lowerCompound.c_str(), "benzene") == 0)
return
(float) 80.1;
else if
(_stricmp(lowerCompound.c_str(), "ethanol") == 0)
return
(float) 78.3;
else
return
0.0;
}
}


string GetMolecularStructure(string compound)
{

string lowerCompound = toLowerString(compound);

if
(_stricmp(lowerCompound.c_str(), "water") == 0)
return
"H2O";
else if
(_stricmp(lowerCompound.c_str(), "benzene") == 0)
return
"C6H6";
else if
(_stricmp(lowerCompound.c_str(), "ethanol") == 0)
return
"C2H5OH";
else
return
"";
}


double
GetMolecularWeight(string compound)
{

string lowerCompound = toLowerString(compound);

if
(_stricmp(lowerCompound.c_str(), "water") == 0)
return
18.015;
else if
(_stricmp(lowerCompound.c_str(), "benzene") == 0)
return
78.1134;
else if
(_stricmp(lowerCompound.c_str(), "ethanol") == 0)
return
46.0688;
else
return
0.0;
}

private
:
//Helper function
string toLowerString(string& input)
{

int
length = input.length();
string output;
for
(int i = 0; i < length; i++)
{

output += tolower(input[i]);
}

return
output;
}
};


//The 'Adapter' class
class RichCompound : public Compound
{

public
:
RichCompound(string name) : Compound(name)
{

bank_ = new ChemicalDatabank();
}

virtual
~RichCompound()
{

delete
bank_;
}

void
Display()
{

boilingPoint_ = bank_->GetCriticalPoint(chemical_, "B");
meltingPoint_ = bank_->GetCriticalPoint(chemical_, "M");
molecularWeight_ = bank_->GetMolecularWeight(chemical_);
molecularFormula_ = bank_->GetMolecularStructure(chemical_);

Compound::Display();
cout << " Formula : " << molecularFormula_ << endl;
cout << " Weight : " << molecularWeight_ << endl;
cout << " Melting Pt : " << meltingPoint_ << endl;
cout << " Boiling Pt : " << boilingPoint_ << endl;
}

private
:
ChemicalDatabank* bank_;
RichCompound(); //dis-allow default constructor
};

int
main()
{

Compound unknown("Unknown");
unknown.Display();

RichCompound water("Water");
water.Display();

RichCompound benzene("Benzene");
benzene.Display();

RichCompound ethanol("Ethanol");
ethanol.Display();

RichCompound zahid("Zahid");
zahid.Display();

return
0;
}






The output is as follows:



For more details, please see:

http://www.dofactory.com/Patterns/PatternAdapter.aspx
http://www.patterndepot.com/put/8/adapter.pdf