Showing posts with label Design Pattern. Show all posts
Showing posts with label Design Pattern. Show all posts

Thursday, January 24, 2013

Advantages of Design Pattern

Some of the advantages of design pattern are as follows,

  • Program Organization
  • Code Quality
  • Design Reuse
  • Code Reuse
  • Part of design vocabulary
  • Maintainability

Saturday, October 1, 2011

singleton pattern implementation


singleton design pattern implementation in C++

Singleton is one of the commonly used patterns in object oriented developments. In this article I am discussing abt this pattern in general and how we can implement this pattern with C++.

Introduction

Suppose we have to use a single object of a class throughout the lifetime of an application. In C++, it is possible to declare a global object, which can be used anywhere inside the program. But a good object oriented design strictly prohibits the use of global variables or methods, since they are against the fundamental principles of object orientation like data encapsulation or data hiding. More over, most latest object oriented programming languages like JAVA or C# do not support global variables or functions.

Another practical solution to get a single object is by declaring a class, which contains only static methods. A static class is loaded into memory when the execution of the program starts and it remains there till the application ends. Remember that for invoking a static method of a class, it is not necessary to create an instance of the class. But remember that a class with only static methods and variables are not a good object oriented design. A class of static methods unfortunately breaks down to a list of functions or utilities.

When we want to create only one instance of a class in a truly object oriented fashion by adhering to the basic principles of object oriented programming, the Singleton patterns are used. The Singleton Pattern comes under that classification of Creational Pattern, which deals with the best ways to create objects. The Singleton Design pattern is used, where only one instance of an object is needed throughout the lifetime of an application. The Singleton class is instantiated at the time of first access and same instance is used thereafter till the application quits.

There are very good non-software examples available in real world for Singleton patterns. The office of the Principal of my college is a Singleton. The University specifies the means by which a principal is selected, limits the term of office, and defines the order of succession. As a result, there can be at most one active principal at any given time. Regardless of the personal identity of the principal, the title, "The Principal" is a global point of access that identifies the person in the office.

The Singletons are often used to control access to resources such as database connections or sockets. Suppose we have a license for only one connection for our database. A Singleton connection object makes sure that only one connection can be made at any time.

It is pretty easy to implement the Singleton Pattern in any object oriented programming languages like C++, JAVA or C#. There are lots of different ways to implement the Singleton Pattern. But by using a private constructor and a static method to create and return an instance of the class is a popular way for implementing Singleton Pattern. The UML representation of a Singleton Pattern is shown below.
The Singleton design pattern ensures only one instance of a class in an application (more generally it provides a framework to control the instantiations of a particular class, so that more than one instantiation could be provided, but under the control of the Singleton class). The GoF book discusses Singleton patterns, while Meyers discusses general techniques for limiting object instantiation in item 26 of More Effective C++. In Singleton classes, all of the regular constructors are publicly disabled (put in the private section), and access to the singleton object is through a static method which creates a controlled instance of the class and returns a reference to this controlled instance.

An example that Meyers uses is:

class Printer {
   public:
      static Printer& thePrinter();
      // ...
   private:
      Printer(); // no public creation of Printer objects
      Printer (const Printer& rhs);
      // ...
};
Printer& Printer::thePrinter() {
   static Printer p;
   return p;
}
// example usage:
Printer::thePrinter().reset();
Printer::thePrinter().submitJob(buffer);

Note that this example implementation code will not work if the Singleton is accessed in a multi-threaded environment, since there may be two (or more) threads trying to simultaneously access the Singleton for the first time, causing a conflict in the static instance creation. Some form of mutex protection must be provided in this scenario.

There are many flavors of Singletone and quite a few subtle complexities, although the general principle of the pattern makes it one of the easiest to understand. One potential complexity is controlled destruction of the internal Singleton instance (i.e. when is it destructed and in what order compared to other Singletons or global objects).

Example:

Wednesday, July 20, 2011

Builder Pattern

The builder pattern is an object creation software design pattern. The intention is to abstract steps of construction of objects so that different implementations of these steps can construct different representations of objects. Often, the builder pattern is used to build products in accordance to the composite pattern, a structural pattern.
  • Separate the specification of how to construct a complex object from the representation of the object.
  • The same construction process can create different representations.
  • Example:
    1. A converter reads files from one file format (i.e. RTF).
    2. It should write them to one of several output formats (ascii, LaTeX, HTML, etc.) 
  • No limit on the number of possible output formats.
    1. It must be easy to add a new “conversion” without modifying the code for the reader.

Requirements:
  • Single Responsibility Principle.
    1. Same reader for all output formats
    2. Output format chosen once in code
  • Open-Closed Principle.
    1. Easy to add a new output format.
    2. Addition does not change old code
  • Dynamic choice of output format.
The Problem:



Participants:
  • The reader: reads the input file, and invokes the converter to produce the output file.
  • The output file is the final product of the construction.
  • The converter is the builder that builds the final product in a complex way.

Solutions:
  • We should return a different object depending on the output format:
    1. HTMLDocument, RTFDocument, . . .
  • Separate the building of the output from reading the input
  • Write an interface for such a builder.
  • Use inheritance to write different concrete builders
UML Representation:

The Solution Code:

//Builder Interface-

class Builder {
virtual void writeChar(char c) { }
virtual void setFont(Font *f) { }
virtual void newPage() { }
};

//Here’s a concrete builder-

class HTMLBuilder : public Builder {
private:
HTMLDocument *doc;
public:
HTMLDocument *getDocument() {
return doc;
}
void writeChar(char c) {
// ...
}
void setFont(Font *f) {
// ...
}
void newPage() {
//...
}
}

The converter uses a builder-

class Converter {
void convert(Builder *b) {
while (t = read_next_token())
switch (o.kind) {
case CHAR: b->writeChar(o);
break;
case FONT: b->setFont(o);
break;
// other kinds
}
}
};

//And this is how the converter is used-
RTFBuilder *b = new RTFBuilder;
converter->convert(b);
RTFDocument *d = b->getDocument();

Comments:
  • This pattern is useful whenever the creation of an object is complex and requires many different steps.
    1. In the example, the creation of HTMLDocument is performed step by step as the tokens are read from the file.
    2. Only at the end the object is ready to be used.
  • Therefore, we separate the creation of the object from its use later on.
  • The final object is created with one single step at the end of the creation procedure.
    1. In this case, it is easier to check consistency of the creation parameters at once.
    2. example: create a Square, using the interface of a Rectangle.
       a. The user sets Height and Width in the builder, then tries to build the Square, and if they are different gets an exception telling what went wrong.

Intent:

Define an interface for creating an object, but let subclasses
decide which class to instantiate
  • Also known as Virtual Constructor.
  • The idea is to provide a virtual function to create objects of a class hierarchy.
  • each function will then know which class to instantiate.
Example:

Consider a framework for an office suite:
  • Typical classes will be Document and Application.
  • there will be different types of documents, and different types of applications.
  • for example: Excel and PowerPoint are applications, excel sheet and presentation are documents.
  • all applications derive from the same abstract class Application.
  • all documents derive from the same abstract class Document.
  • we have parallel hierarchies of classes.
  • every application must be able to create its own document object.
Example in UML


Participants:
  • Product (Document) - defines the interface of the objects the factory method creates
  • ConcreteProduct (MyDocument) - implements the Product’s interface
  • Creator (Application) - declares the factory method
  • ConcreteCreator (MyApplication) - overrides the factory method to return an instance of a ConcreteProduct
UML representation :
Collaboration:
  • The client creates the Director object and configures it with the desired Builder object.
  • Director notifies the builder whenever a part of the product should be built.
  • Builder handles requ ests from the director and adds parts to the product.
  • The client retrieves the product from the builder.
Useful Tips:

  • Builder focuses on constructing a complex object step by step. Abstract Factory emphasizes a family of product objects (either simple or complex). Builder returns the product as a final step, but as far as the Abstract Factory is concerned, the product gets returned immediately.
  • Builder often builds a Composite.
  • Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.
  • Sometimes creational patterns are complementary: Builder can use one of the other patterns to implement which components are built. Abstract Factory, Builder, and Prototype can use Singleton in their implementations.
  • Builders are good candidates for a fluent interface.
Rules of thumb:
  • Sometimes creational patterns are complementory: Builder can use one of the other patterns to implement which components get built. Abstract Factory, Builder, and Prototype can use Singleton in their implementations. [GoF, p81, 134]
  • Builder focuses on constructing a complex object step by step. Abstract Factory emphasizes a family of product objects (either simple or complex). Builder returns the product as a final step, but as far as the Abstract Factory is concerned, the product gets returned immediately. [GoF, p105]
  • Builder often builds a Composite. [GoF, p106]
  • Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed. [GoF, p136]
Sample Code :

click here to see the implementation of the builder pattern.


Tuesday, July 19, 2011

Design Pattern in C++

Following points are covered under design pattern guides


  • Abstract Factory 
  • Adapter 
  • Bridge 
  • Builder
  • Chain of Responsibility
  • Command 
  • Composite 
  • Decorator 
  • Façade 
  • Factory Method 
  • Flyweight 
  • Interpreter 
  • Iterator 
  • Mediator 
  • Memento 
  • Observer 
  • Prototype 
  • Proxy
  • Singleton 
  • State 
  • Strategy 
  • Template Method 
  • Visitor
.   Example of Design pattern with pictures and example.

Monday, July 18, 2011

Bridge Pattern


The bridge pattern is a design pattern which is meant to "decouple an abstraction from its implementation so that the two can vary independently". The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.

When a class varies often, the features of object-oriented programming become very useful because changes to a program's code can be made easily with minimal prior knowledge about the program. The bridge pattern is useful when both the class as well as what it does vary often. The class itself can be thought of as the implementation and what the class can do as the abstraction. The bridge pattern can also be thought of as two layers of abstraction.
The bridge pattern is often confused with the adapter pattern. In fact, the bridge pattern is often implemented using the class adapter pattern, e.g. in the Java code below.
Variant: The implementation can be decoupled even more by deferring the presence of the implementation to the point where the abstraction is utilized.

Intent
Decouple an abstraction from its implementation so that the two can vary independently.
Publish interface in an inheritance hierarchy, and bury implementation in its own inheritance hierarchy. Beyond encapsulation, to insulation

Problem
Hardening of the software arteries” has occurred by using subclassing of an abstract base class to provide alternative implementations. This locks in compile-time binding between interface and implementation. The abstraction and implementation cannot be independently extended or composed.

Motivation
Consider the domain of “thread scheduling”.



There are two types of thread schedulers, and two types of operating systems or “platforms”. Given this approach to specialization, we have to define a class for each permutation of these two dimensions. If we add a new platform (say … Java’s Virtual Machine), what would our hierarchy look like?



What if we had three kinds of thread schedulers, and four kinds of platforms? What if we had five kinds of thread schedulers, and ten kinds of platforms? The number of classes we would have to define is the product of the number of scheduling schemes and the number of platforms.
The Bridge design pattern proposes refactoring this exponentially explosive inheritance hierarchy into two orthogonal hierarchies – one for platform-independent abstractions, and the other for platform-dependent implementations.



Another example can be seen like that-
Inheritance hierarchies can be hierarchies of abstarctions (concepts) or hierarchies of implementations. For example: 



Mixing concepts with implementations can lead to hierarchies that are confusing and difficult to maintain.
It could lead to an exponential number of subclasses and soon we will have an exploding class hierarchy.

Discussion

Decompose the component’s interface and implementation into orthogonal class hierarchies. The interface class contains a pointer to the abstract implementation class. This pointer is initialized with an instance of a concrete implementation class, but all subsequent interaction from the interface class to the implementation class is limited to the abstraction maintained in the implementation base class. The client interacts with the interface class, and it in turn “delegates” all requests to the implementation class.
The interface object is the “handle” known and used by the client; while the implementation object, or “body”, is safely encapsulated to ensure that it may continue to evolve, or be entirely replaced (or shared at run-time.

Use the Bridge pattern when:

  • you want run-time binding of the implementation,
  • you have a proliferation of classes resulting from a coupled interface and numerous implementations,
  • you want to share an implementation among multiple objects,
  • you need to map orthogonal class hierarchies.
  • You want to avoid a permanent binding between an abstraction and its implementation.
  • Both the abstractions and their implementations should be extensible by subclassing
  • Changes in the implementation of an abstraction should have no impact on clients – their code should not have to be recompiled
  • (C++) you want to hide the implementation of an abstraction completely from clients (in C++, the representation of a class is visible in the class interface)
  • You have a proliferation of classes as shown earlier in the motivation.





    Consequences include:

    • decoupling the object’s interface,
    • improved extensibility (you can extend (i.e. subclass) the abstraction and implementation hierarchies independently),
    • hiding details from clients.  

    Bridge is a synonym for the “handle/body” idiom. This is a design mechanism that encapsulates an implementation class inside of an interface class. The former is the body, and the latter is the handle. The handle is viewed by the user as the actual class, but the work is done in the body. “The handle/body class idiom may be used to decompose a complex abstraction into smaller, more manageable classes. The idiom may reflect the sharing of a single resource by multiple classes that control access to it (e.g. reference counting).”

    Structure

    The Client doesn’t want to deal with platform-dependent details. The Bridge pattern encapsulates this complexity behind an abstraction “wrapper”.
    Bridge emphasizes identifying and decoupling “interface” abstraction from “implementation” abstraction.



    Example

    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.



    Check list
    • Decide if two orthogonal dimensions exist in the domain. These independent concepts could be: abstraction/platform, or domain/infrastructure, or front-end/back-end, or interface/implementation.
    • Design the separation of concerns: what does the client want, and what do the platforms provide.
    • Design a platform-oriented interface that is minimal, necessary, and sufficient. Its goal is to decouple the abstraction from the platform.
    • Define a derived class of that interface for each platform.
    • Create the abstraction base class that “has a” platform object and delegates the platform-oriented functionality to it.
    • Define specializations of the abstraction class if desired.

    Rules of thumb:
    • 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.
    Example Code

    Discussion. The motivation is to decouple the Time interface from the Time implementation, while still allowing the abstraction and the realization to each be modelled with their own inheritance hierarchy. The implementation classes below are straight-forward. The interface classes are a little more subtle. Routinely, a Bridge pattern interface hierarchy “hasa” implementation class. Here the interface base class “hasa” a pointer to the implementation base class, and each class in the interface hierarchy is responsible for populating the base class pointer with the correct concrete implementation class. Then all requests from the client are simply delegated by the interface class to the encapsulated implementation class.

    /*
     * Sample Code describing usage of bridge Design Pattern
     */

    #include <iostream>
    #include <iomanip.h>
    #include <string>

    using namespace std;

    class CTimeImp {
         public:
               CTimeImp(int hr, int min) {
                    m_nHr = hr;
                    m_nMin = min;
               }
               virtual void tell() {
                    cout << "time is " << m_nHr << m_nMin << endl;
               }
         protected:
               int m_nHr, m_nMin;
    };

    class CCivilianCTimeImp: public CTimeImp {
         public:
               CCivilianCTimeImp(int hr, int min, int pm): CTimeImp(hr, min) {
                    if (pm) {
                         strcpy(m_cWhichM, " PM");
                    }   
                    else {
                         strcpy(m_cWhichM, " AM");
                    }
               }
         /*
          * virtual
          */
               void tell() {
                    cout << "time is " << m_nHr << ":" << m_nMin << m_cWhichM << endl;
               }
         protected:
               char m_cWhichM[4];
    };

    class CZuluCTimeImp: public CTimeImp {
         public:
               CZuluCTimeImp(int hr, int min, int zone): CTimeImp(hr, min) {
                    if (zone == 5) {
                         strcpy(m_cZone, " Eastern Standard Time");
                    }
                    else if (zone == 6) {
                         strcpy(m_cZone, " Central Standard Time");
                    }
               }
               /*
                * virtual
                */
               void tell() {
                    cout << "time is " << m_nHr << m_nMin << m_cZone << endl;
               }
         protected:
               char m_cZone[30];
    };

    class CTime {
         public:
               CTime(){
              }
               CTime(int hr, int min) {
                    imp_ = new CTimeImp(hr, min);
               }
               virtual void tell() {
                    imp_->tell();
               }
         protected:
               CTimeImp *imp_;
    };

    class CCivilianTime: public CTime {
      public:
        CCivilianTime(int hr, int min, int pm) {
            imp_ = new CCivilianCTimeImp(hr, min, pm);
        }
    };

    class CZuluTime: public CTime {
         public:
               CZuluTime(int hr, int min, int zone) {
                    imp_ = new CZuluCTimeImp(hr, min, zone);
               }
    };

    int main() {    // main begins
         CTime *times[3];
         times[0] = new CTime(14, 30);
         times[1] = new CCivilianTime(2, 30, 1);
         times[2] = new CZuluTime(14, 30, 6);
         for (int i = 0; i < 3; i++) {
               times[i]->tell();
         }
         return 0;
    }    //main ends

    /*
    [sgupta@rhel55x86 bridge]$ ./bridge
    time is 1430
    time is 2:30 PM
    time is 1430 Central Standard Time
    [sgupta@rhel55x86 bridge]$
    */