top of page

Design Pattern


what is design pattern?

Design patterns are typical solutions to commonly occurring problems in software design. They are like pre-made blueprints that you can customize to solve a recurring design problem in your code.

Patterns are often confused with algorithms, because both concepts describe typical solutions to some known problems. While an algorithm always defines a clear set of actions that can achieve some goal, a pattern is a more high-level description of a solution. The code of the same pattern applied to two different programs may be different.

Types of design pattern:

1>Creational patterns

2>Structural patterns

3>Behavioral patterns

Creational patterns:

Creational patterns provide various object creation mechanisms, which increase flexibility and reuse of existing code.

Types of Creational patterns:

Singleton

Factory Method

Abstract Factory

Builder

Prototype

Singleton Pattern:

Singleton Pattern is a creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this instance.


Singleton classes are used for logging, driver objects, caching and thread pool, database connections.


Example:

#include <iostream>
#include <string>
using namespace std;
class singleton {
    private:
        static singleton *ptr;
        singleton()
        {
            cout<<"In deafult constructor"<<endl;
        }
    public:
        singleton (const singleton &obj) = delete;
        singleton& operator=(const singleton &obj) = delete;
        static singleton * GetInstance();
        void display()
        {
            cout<<"I am in sigleton class"<<endl;
        }
};
singleton * singleton::ptr = NULL;
singleton * singleton::GetInstance()
{
    if(ptr == NULL)
    {
        ptr = new singleton();
    }
    return ptr;
}
int main()
{
    singleton *obj = singleton::GetInstance();
    obj->display();
    singleton *obj2 = singleton::GetInstance();
    //obj2 = obj;
    obj2->display();
    return 0;
}

Comments


bottom of page