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)
loan_.HasGoodCredit(cust, amount);

if
(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

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

Logical Operators: AND(&&) OR(||) NOT(!) in c++

Logical Operators: AND(&&) OR(||) NOT(!) in c++



To understand this chapter better, first go through relational operators. In a program, we often need to test more than one condition. To simplify this logical operators were introduced. In your school you might have learnt Boolean Algebra (Logic).


The three logical operators ( AND, OR and NOT ) are as follows:


1) AND (&&) : Returns true only if both operand are true.
2) OR (||) : Returns true if one of the operand is true.
3) NOT (!) : Converts false to true and true to false.

OperatorOperator's NameExampleResult
&&AND3>2 && 3>11(true)
&&AND3>2 && 3<10(false)
&&AND3<2 && 3<10(false)
||OR3>2 && 3>11(true)
||OR3>2 && 3<11(true)
||OR3<2 && 3<10(false)
!NOT!(3==2)1(true)
!NOT!(3==3)0(false)


/* A c++ program example that demonstrate the working of logical operators. */


// Program 1

#include <iostream>

using namespace std;

int main ()
{
    cout << "3 > 2 && 3 > 1: " << (3 > 2 && 3 > 1) << endl;
    cout << "3 > 2 && 3 < 1: " << (3 > 2 && 3 < 1) << endl;
    cout << "3 < 2 && 3 < 1: " << (3 < 2 && 3 < 1) << endl;
    cout << endl;
    cout << "3 > 2 || 3 > 1: " << (3 > 2 || 3 > 1) << endl;
    cout << "3 > 2 || 3 < 1: " << (3 > 2 || 3 < 1) << endl;
    cout << "3 < 2 || 3 < 1: " << (3 < 2 || 3 < 1) << endl;
    cout << endl;
    cout << "! (3 == 2): " << ( ! (3 == 2) ) << endl;
    cout << "! (3 == 3): " << ( ! (3 == 3) ) << endl;

    return 0;
}


In earlier chapter Selection Statement (if-else if-else), we were required to check two conditons: for username and password. If both username and password are correct then only "You are logged in!" message appears. We checked these two condition using nested if-else statement. However i told you at the end of that chapter that in the "Program 1" nesting can be avoided by using logical operator. Here we will rewrite the "Program 1" of Selection Statement (if-else if-else) using logical operator.

/* A c++ program example that uses a logical operator in selection statement if-else.*/


// Program 2

#include <iostream>
#include <string>

using namespace std;

const string userName = "computergeek";
const string passWord = "break_codes";

int main ()
{
    string name, pass;

    cout << "Username: ";
    cin >> name;

    cout << "Password: ";
    cin >> pass;

    if (name == userName && pass == passWord)
    {
        cout << "You are logged in!" << endl;
    }

    else
        cout << "Incorrect username or password." << endl;

    return 0;
}


/* A simple c++ program example that uses AND logical operator */


// Program 3

#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
    int first, second, third;

    cout << "Enter three integers." << endl;

    cout << "First "<< setw (3) << ": ";
    cin >> first;

    cout << "Second "<< setw (2) << ": ";
    cin >> second;

    cout << "Third "<< setw (3) << ": ";
    cin >> third;

    if (first > second && first > third)
        cout << "first is greater than second and third." << endl;

    else if (second > first && second > third)
        cout << "second is greater than first and third." << endl;

    else if (third > first && third > second)
        cout << "third is greater than first and second." << endl;

    else
        cout << "first, second and third are equal." << endl;

    return 0;
}

/* A simple c++ program example that uses OR logical operator*/


// Program 4

#include <iostream>

using namespace std;

int main ()
{
    char agree;

    cout << "Would you like to meet me (y/n): ";
    cin >> agree;

    if (agree == 'y' || agree == 'Y')
    {
        cout << "Your name: ";
        string name;
        cin >> name;
        cout << "Glad to see you, "+name << endl;
    }

    else if (agree == 'n' || agree == 'N')
        cout << "See you later!" << endl;

    else
        cout << "Please enter 'y' or 'n' for yes or no." << endl;

    return 0;
}


/* A simple c++ program example that uses NOT logical operator*/


// Program 5

#include <iostream>

using namespace std;

int main ()
{
    char agree;

    cout << "Would you like to meet me?" << endl;
    cout << "Press 'y' for yes and any other character for no: ";
    cin >> agree;

    if ( ! (agree == 'y' || agree == 'Y') )
    {
        cout << "See you later!" << endl;
    }

    else
    {
        cout << "Your name: ";
        string name;
        cin >> name;
        cout << "Glad to see you, "+name << "!" << endl;
    }

    return 0;
}

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:

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

Check out this stream