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

State Design Pattern in C++ for a Music System

State Design pattern allows an object to change it's behavior based on its internal State.The Object will appear to change its class.
State Design Pattern in C++ to implement state machine of a Music Player System.
classes used:
MusicSystem -> is the current state context manager class.
State -> is the base class of all states classes.
OFFState -> is the concrete class derived from State.
ONState -> is the concrete class derived from State.
PAUSEDState ->is the concrete class derived from State.
Example:
#include<iostream>
using namespace std;

//current_context class
class State;
class MusicSystem
{
private:
    State *currentState;//to store current state.
   
public:
    enum statesEnum
        {
        ST_STOPPED,
        ST_PLAYING,
        ST_PAUSEDState
        };
public:
    MusicSystem();

    void stopMusic();
    void playMusic();
    void playNextTrack();
    void playPreviousTrack();
    void pauseMusic();
    void setCurrentContext(statesEnum state);
};

//abstract state class
class State
{
public:
    //MusicSystem's pointer is passed so that setCurrentState can be called.
    virtual void off(MusicSystem *ms){cout<<"Already Stopped."<<endl;}
    virtual void play(MusicSystem* ms){cout<<"Already Playing."<<endl;}
    virtual void playNextTrack(MusicSystem* ms){cout<<"Can not play Next in off/paused state."<<endl;}
    virtual void playPreviousTrack(MusicSystem* ms){cout<<"Can not play Previous in off/paused state."<<endl;}
    virtual void pause(MusicSystem* ms){cout<<"Can not Switch to pause in stopped state."<<endl;}
};
//concrete state class on
class OFFState:public State
{
public:
    void play(MusicSystem *ms);
};

//concrete state class off
class ONState:public State
{
public:
    void off(MusicSystem *ms);
    void playNextTrack(MusicSystem *ms);
    void playPreviousTrack(MusicSystem *ms);
    void pause(MusicSystem* ms);
};
//concrete class pause
class PAUSEDState:public State
{
public:
    void off(MusicSystem *ms);
    void playNextTrack(MusicSystem *ms);
    void playPreviousTrack(MusicSystem *ms);
    void play(MusicSystem* ms);
   
};

MusicSystem::MusicSystem()
{
    currentState=new OFFState;
}
void MusicSystem::stopMusic()
{
    currentState->off(this);  
}
void MusicSystem::playMusic()
{
    currentState->play(this);  
}
void MusicSystem::playNextTrack()
{
    currentState->playNextTrack(this);  
}
void MusicSystem::playPreviousTrack()
{
    currentState->playPreviousTrack(this);  
}
void MusicSystem::pauseMusic()
{
    currentState->pause(this);
}


    void OFFState::play(MusicSystem *ms)
    {
    cout<<"Turning to Play."<<endl;
    ms->setCurrentContext(MusicSystem::ST_PLAYING);
    delete this;
    }
    void ONState::off(MusicSystem *ms)
    {
    cout<<"Turning to Stopped."<<endl;
    ms->setCurrentContext(MusicSystem::ST_STOPPED);
    delete this;
    }
    void ONState::playNextTrack(MusicSystem *ms)
    {
    cout<<"Playing next track..."<<endl;
    }
    void ONState::playPreviousTrack(MusicSystem *ms)
    {
    cout<<"Playing previous track..."<<endl;
    }
    void ONState::pause(MusicSystem* ms)
    {
    cout<<"Switching to Pause."<<endl;   
    ms->setCurrentContext(MusicSystem::ST_PAUSEDState);
    }
   
    void PAUSEDState::off(MusicSystem *ms)
    {
    cout<<"Turning to Stopped."<<endl;
    ms->setCurrentContext(MusicSystem::ST_STOPPED);
    delete this;
    }
    void PAUSEDState::playNextTrack(MusicSystem *ms)
    {
    cout<<"Playing next track..."<<endl;
    }
    void PAUSEDState::playPreviousTrack(MusicSystem *ms)
    {
    cout<<"Playing previous track..."<<endl;
    }
    void PAUSEDState::play(MusicSystem* ms)
    {
    cout<<"Switching to Play."<<endl;   
    ms->setCurrentContext(MusicSystem::ST_PLAYING);
    }


void MusicSystem::setCurrentContext(statesEnum state)
    {
        if(state==ST_STOPPED)
    {
    currentState=new OFFState;
    }
    else if(state == ST_PLAYING)
    {
    currentState=new ONState();
    }
    else if(state == ST_PAUSEDState)
    {
    currentState=new PAUSEDState();
    }
    else
    {
    cout<<"Unknown state"<<endl;
    }
    }


//main
int main()
{
MusicSystem ms;

ms.MusicSystem::stopMusic();
ms.MusicSystem::stopMusic();
ms.MusicSystem::pauseMusic();
ms.MusicSystem::playNextTrack();
ms.MusicSystem::playPreviousTrack();

ms.MusicSystem::playMusic();
ms.MusicSystem::playMusic();
ms.MusicSystem::pauseMusic();
ms.MusicSystem::playNextTrack();
ms.MusicSystem::playPreviousTrack();

ms.MusicSystem::stopMusic();
ms.MusicSystem::playNextTrack();
ms.MusicSystem::playPreviousTrack();

return 0;
}
/*
Already Stopped.
Already Stopped.
Can not Switch to pause in stopped state.
Can not play Next in off/paused state.
Can not play Previous in off/paused state.
Turning to Play.
Already Playing.
Switching to Pause.
Playing next track...
Playing previous track...
Turning to Stopped.
Can not play Next in off/paused state.
Can not play Previous in off/paused state.
*/

Factory Method Design pattern in C++ and Abstract Factory Design pattern in CPP

"Factory Method Design pattern" is used when many derived classes are derived from a common base class and object of which derived class should be instantiated is only known at run time.
One way to achieve it by providing a static method in base class itself which returns pointer to the same base class.
When client needs to create object it calls this static method to create object of required derived class by passing type of subclass as string.And need not instantiate specific object by using subclass constructor.
Benefit of factory design pattern is that when new type is added then changes required only at one place where object is created ie only new case is added in factory method.
Intent of factory method is to provide a method to create objects, But defer the object creation to derive class based on some condition or configuration which acts like a virtual constructor. It decouples client from object creation.

Another variation of Factory pattern is "Abstract factory pattern".
In abstract factory design pattern an interface(Abstract base class) is provided to create object, But, let the subclass to decide which class to instantiate.
In example ShapeFactory is the abstract base class. And, object is created based on type passed.
Factory design pattern: We have factory that produces objects that from a particular base class.
Abstract Factory Design Pattern: We have factory that creates other factories and these factories in turn creates objects derived from other base class. Abstract factory needed when when we want to create collection of related objects and not just one object.

"Factory Method Design pattern" Implementation in C plus plus
#include<iostream>
using namespace std;

class Shape
{
public:
    virtual void whichShape()=0;
    static Shape* getShape(string s);//Factory method to create Object
};
class Rectangle:public Shape
{
public:
    void whichShape(){cout<<"Rectangle"<<endl;}
   
};
class Circle:public Shape
{
public:
    void whichShape(){cout<<"Circle"<<endl;}
   
};
Shape* Shape::getShape(string s)
{
if(s=="Rectangle")
    return new Rectangle();
if(s=="Circle")
    return new Circle();

}
int main()
{
//At run time requested type is Rectangle
Shape *s1= Shape::getShape("Rectangle");
s1->whichShape();
//At run time requested type is Circle
Shape *s2= Shape::getShape("Circle");
s2->whichShape();
return 0;
}
 //---------------------------
"Abstract Factory  Design pattern" Implementation in C++
#include<iostream>
using namespace std;

class Shape
{
public:
    virtual void whichShape()=0;
//    static Shape* getShape(string s);
};
class Rectangle:public Shape
{
public:
    void whichShape(){cout<<"Rectangle"<<endl;}
   
};
class Circle:public Shape
{
public:
    void whichShape(){cout<<"Circle"<<endl;}
   
};
class ShapeFactory
{
public:
    static Shape* getShape(string s);//Factory1
    static Shape* getEdgyShape(string s);//Factory2
    static Shape* getRoundedShape(string s);//Factory3
};
Shape* ShapeFactory::getShape(string s)
{
if(s=="Rectangle")
    return new Rectangle();
if(s=="Circle")
    return new Circle();

}
int main()
{
//At run time requested type is Rectangle
ShapeFactory* sf = new ShapeFactory();
Shape* s1 = sf->getShape("Rectangle");
s1->whichShape();
//At run time requested type is Circle
ShapeFactory* sf2 = new ShapeFactory();
Shape* s2 = sf2->getShape("Circle");
s2->whichShape();

return 0;
}
 

State Design Pattern code in C++

State Design Pattern to design a Music System in C++ language.
#include<iostream>
using namespace std;

//current_context class
class State;
class MusicSystem
{
private:
    State *currentState;
public:
    MusicSystem();

    void stopMusic();
    void playMusic();
    void playNextTrack();
    void playPreviousTrack();
    void setCurrentContext(State* s)
    {
    currentState=s;
    }
};

//abstract state class

class State
{
public:
    virtual void offState(MusicSystem *ms){cout<<"Already Stopped"<<endl;}
    virtual void onState(MusicSystem* ms){cout<<"Already Playing"<<endl;}
    virtual void playNextTrack(MusicSystem* ms){cout<<"Can not play Next in off state."<<endl;}
    virtual void playPreviousTrack(MusicSystem* ms){cout<<"Can not play Previous in off state."<<endl;}
};
//concrete state class on
class OFF:public State
{
public:
    void onState(MusicSystem *ms);
};

//concrete state class off
class ON:public State
{
public:
    void offState(MusicSystem *ms);
    void playNextTrack(MusicSystem *ms);
    void playPreviousTrack(MusicSystem *ms);
};

MusicSystem::MusicSystem()
{
    currentState=new OFF;
}
void MusicSystem::stopMusic()
{
    currentState->offState(this);   
}
void MusicSystem::playMusic()
{
    currentState->onState(this);   
}
void MusicSystem::playNextTrack()
{
    currentState->playNextTrack(this);   
}
void MusicSystem::playPreviousTrack()
{
    currentState->playPreviousTrack(this);   
}


    void OFF::onState(MusicSystem *ms)
    {
    cout<<"Turning from stopped to Play."<<endl;
    ms->setCurrentContext(new ON());
    delete this;
    }
    void ON::offState(MusicSystem *ms)
    {
    cout<<"Turning from Playing to Stopped."<<endl;
    ms->setCurrentContext(new OFF());
    delete this;
    }
    void ON::playNextTrack(MusicSystem *ms)
    {
    cout<<"Playing next track..."<<endl;
    //ms->setCurrentContext(new OFF());
    //delete this;
    }
    void ON::playPreviousTrack(MusicSystem *ms)
    {
    cout<<"Playing previous track..."<<endl;
    //ms->setCurrentContext(new OFF());
    //delete this;
    }


//main
int main()
{
MusicSystem ms;

ms.MusicSystem::stopMusic();
ms.MusicSystem::stopMusic();
ms.MusicSystem::stopMusic();
ms.MusicSystem::playNextTrack();
ms.MusicSystem::playPreviousTrack();

ms.MusicSystem::playMusic();
ms.MusicSystem::playMusic();
ms.MusicSystem::playMusic();
ms.MusicSystem::playNextTrack();
ms.MusicSystem::playPreviousTrack();

ms.MusicSystem::stopMusic();
ms.MusicSystem::playNextTrack();
ms.MusicSystem::playPreviousTrack();

return 0;
}

Simple logger class implementation code example in c++

//main.cpp
#include "Logger.h"
int main(int argc, char *argv[])
{
    string message1 = "logg message 1 ...";
    string message2 = "logg message 2 ...";
    int    nNum     = 10;
    CLogger::getLogger()->Log("\nmessage to be logged------------------>\n");
    CLogger::getLogger()->Log(message1);
   
    CLogger::getLogger()->Log("\nmessage to be loggedi again-------------------->\n");
    LOGGER->Log("\nMessage is:%s Number is:%d",message1.c_str(), nNum,"\n");//#define LOGGER CLogger::getLogger()

    CLogger::getLogger()->Log("\nmessage to be loggedi again------------------------>\n");
    CLogger *ptr1;
    ptr1=CLogger::getLogger();
    ptr1->Log("\nMessage Logged\n");           

}
//logger.h
#ifndef CUSTOM_CLogger_H
#define CUSTOM_CLogger_H
#include <fstream>
#include <iostream>
#include <cstdarg>
#include <string>
using namespace std;
#define LOGGER CLogger::getLogger()
/**
 *   Singleton Logger Class.
 */
class CLogger
{
public:
    /**
     *   Logs a message
     *   @param sMessage message to be logged.
     */
    void Log(const std::string& sMessage);
    /**
     *   Variable Length Logger function
     *   @param format string for the message to be logged.
     */
    void Log( const char * format, ... );
        /**
     *   << overloaded function to Logs a message
     *   @param sMessage message to be logged.
     */
    CLogger& operator<<(const string& sMessage );
    /**
     *   Funtion to create the instance of logger class.
     *   @return singleton object of Clogger class..
     */
    static CLogger* getLogger();
private:
    /**
     *    Default constructor for the Logger class.
     */
    CLogger();
    /**
     *   copy constructor for the Logger class.
     */
    CLogger( const CLogger&){};             // copy constructor is private
    /**
     *   assignment operator for the Logger class.
     */
    CLogger& operator=(const CLogger& ){ return *this;};  // assignment operator is private
    /**
     *   Log file name.
     **/
    static const std::string m_sFileName;
    /**
     *   Singleton logger class object pointer.
     **/
    static CLogger* m_pThis;
    /**
     *   Log file stream object.
     **/
    static ofstream m_Logfile;
};
#endif
//logger.cpp
#include "Logger.h"
//#include"Utilities.h"
const string CLogger::m_sFileName = "Log.txt";
CLogger* CLogger:: m_pThis = NULL;
ofstream CLogger::m_Logfile;
CLogger::CLogger()
{

}
CLogger* CLogger::getLogger(){
    if(m_pThis == NULL){
        m_pThis = new CLogger();
        m_Logfile.open(m_sFileName.c_str(), ios::out | ios::app );
    }
    return m_pThis;
}

void CLogger::Log( const char * format, ... )
{
    char sMessage[256];
    va_list args;
    va_start (args, format);
    vsprintf (sMessage,format, args);
//    m_Logfile <<"\n"<<Util::CurrentDateTime()<<":\t";
    m_Logfile << sMessage;
    va_end (args);
}

void CLogger::Log( const string& sMessage )
{
    //m_Logfile <<"\n"<<Util::CurrentDateTime()<<":\t";
    m_Logfile << sMessage;
}

CLogger& CLogger::operator<<(const string& sMessage )
{
    //m_Logfile <<"\n"<<Util::CurrentDateTime()<<":\t";
    m_Logfile << sMessage;
    return *this;
}
//Log.txt

message to be logged------------------>
logg message 1 ...
message to be loggedi again-------------------->

Message is:logg message 1 ... Number is:10
message to be loggedi again------------------------>

Message Logged
//Courtesy cppcodetips.wordpress.com

Factory Design pattern code example in C++

Factory Design pattern is achieved in 2 ways:
1. By giving a abstract interface class or and giving object create method in concrete class derived from interface class
2. By giving object create method in Factory class
2.  Factory Design pattern: defines interface to create objects. Object creation not required directly by client instead it is created in provided interface. Advantage is that client does not require to know exact class name whose object it wants to create. Also object instantiation is delayed till factory's create() method call so its like virtual constructor as exact class name is not required during compile time.
#include<iostream>
using namespace std;
#include<string.h>
class Button
{
public:
    virtual void paintButton()=0;
};
class OsLinuxButton: public Button
{
public:
    void paintButton()
    {
    cout<<"OsLinuxButton::paintButton"<<endl;
    }   
};
class OsWindowButton: public Button
{
public:
    void paintButton()
    {
    cout<<"OsWindowButton::paintButton"<<endl;
    }   
};
class GuiFactory
{
public:
    virtual Button* createButton(char* but)//No abstract
    {
    if(strcmp(but,"window")==0)
    {
    return new OsWindowButton;
    }
    if(strcmp(but,"linux")==0)
    {
    return new OsLinuxButton;
    }
    }
};
class Factory: public GuiFactory
{
public:
    Button* createButton(char* but)
    {
    if(strcmp(but,"window")==0)
    {
    return new OsWindowButton;
    }
    if(strcmp(but,"linux")==0)
    {
    return new OsLinuxButton;
    }
    }
};

int main()
{
Button *button1;
GuiFactory * guifactory=new Factory;
button1 = guifactory->createButton("window");
button1->paintButton();

Button *button2;
GuiFactory * guifactory2=new Factory;
button2 = guifactory->createButton("linux");
button2->paintButton();
return 0;
}

Example 2:
//Abstract factory Design pattern: defines interface to create family of objects. Object creation not required directly by client instead it is created in provided interface. Advantage is that client does not require to know exact class name whose object it wants to create. Also objectinstantiation is delayed till factory's create() method call so its like virtual constructor as exact class name is not required during compile time.
#include<iostream>
using namespace std;
#include<string.h>
class Button
{
public:
    virtual void paintButton()=0;
};
class OsLinuxButton: public Button
{
public:
    void paintButton()
    {
    cout<<"OsLinuxButton::paintButton"<<endl;
    }  
};
class OsWindowButton: public Button
{
public:
    void paintButton()
    {
    cout<<"OsWindowButton::paintButton"<<endl;
    }  
};
/*
class GuiFactory
{
public:
    virtual Button* createButton(char* but)=0;
};
class Factory: public GuiFactory
{
public:
    Button* createButton(char* but)
    {
    if(strcmp(but,"window")==0)
    {
    return new OsWindowButton;
    }
    if(strcmp(but,"linux")==0)
    {
    return new OsLinuxButton;
    }
    }
};
*/
int main()
{
/*
Button *button1;
GuiFactory * guifactory=new Factory;
button1 = guifactory->createButton("window");
button1->paintButton();

Button *button2;
GuiFactory * guifactory2=new Factory;
button2 = guifactory->createButton("linux");
button2->paintButton();
*/
//Without factory Object is ctreated in client code itself.
//client does new so may effect the code. Separate interface is not defined to create object.
Button *button=new OsLinuxButton;
button->paintButton();

Button *buttonWindow=new OsWindowButton;
buttonWindow->paintButton();
return 0;
}

Abstract factory Design pattern code example in cpp

Abstract factory Design pattern: defines interface to create family of objects. Object creation not required directly by client instead it is created in provided interface. Advantage is that client does not require to know exact class name whose object it wants to create. Also object instantiation is delayed till factory's create() method call so its like virtual constructor as exact class name is not required during compile time.
#include<iostream>
using namespace std;
#include<string.h>
class Button
{
public:
    virtual void paintButton()=0;
};
class OsLinuxButton: public Button
{
public:
    void paintButton()
    {
    cout<<"OsLinuxButton::paintButton"<<endl;
    }   
};
class OsWindowButton: public Button
{
public:
    void paintButton()
    {
    cout<<"OsWindowButton::paintButton"<<endl;
    }   
};
class GuiFactory
{
public:
    virtual Button* createButton(char* but)=0;
};
class Factory: public GuiFactory
{
public:
    Button* createButton(char* but)
    {
    if(strcmp(but,"window")==0)
    {
    return new OsWindowButton;
    }
    if(strcmp(but,"linux")==0)
    {
    return new OsLinuxButton;
    }
    }
};

int main()
{
Button *button1;
GuiFactory * guifactory=new Factory;
button1 = guifactory->createButton("window");
button1->paintButton();

Button *button2;
GuiFactory * guifactory2=new Factory;
button2 = guifactory->createButton("linux");
button2->paintButton();
return 0;
}

Example2:

Singleton Design Pattern example in C++

//Singleton is a creational design pattern.
//A design pattern to provide one and only instance of an object.
//Declare the constructors of the class private.
//Declatre a static public instance of class type.
//Provide a static public method to get the instance
//If instance is NULL then only once create a object else
//return the already created instance
#include<stdio.h>
using namespace std;
class singleton
{
private:
singleton(){printf("Constructor called only once.\n");}
public:
static singleton* instance;
static singleton* getinstance();
};
singleton* singleton::instance=NULL;

singleton* singleton::getinstance()
{
if(instance==NULL)
{
instance = new singleton;//mind the syntax//no singleston s;
}
else
{
return instance;
}
}
int main()
{
//singleton s1;//singleton() is private within this context
singleton *sptr;
sptr=singleton::getinstance();
sptr=singleton::getinstance();
sptr=singleton::getinstance();
sptr=singleton::getinstance();
sptr=singleton::getinstance();
return 0;
}
/*
Constructor called only once.
*/

Observer Design Pattern example in C++


Observer Design Pattern example in C++

//Observer Design pattern Best Example.
//Observer Design pattern is implemented using two classes.
//First is observable or subject class: in this class even occurs and to be notified to the registered observers.
//subject class contains attachObserver(), notifyObserver(),and other task.
//Second class is observer class: class which wants to be notified when some even occurs in observable or subject class.
//observer class contains a pure viryual function notify().
//Example:
//When any event like new blog/article is available in a website it should notify to all the registered users.
//So here Blog will derived from subject class and
//users want to get notified of new articles. So User will be derived from class observer
#include<iostream>
using namespace std;
#include <vector>
#include <typeinfo>
#include <string>

class Subject;//forward declaration

class Observer//class which are interested to get notified
{
public:
    virtual void notify(Subject* s) = 0;//pure virtual function
    virtual ~Observer() {};
};

class Subject//Class in which even take place
{
    vector<Observer *> observers;
protected:
    void notify_observers()
    {
        vector<Observer *>::iterator iter;
        for (iter = observers.begin(); iter != observers.end(); ++iter)
            (*iter)->notify(this);
    }

public:
    virtual ~Subject() {};
    void register_observer(Observer* o)//pusshing the attached observers in a vector
    {
        observers.push_back(o);
    }
};

class Blog : public Subject
{
public:
    Blog()
    {
        cout << "New Article Posted." << "\n";
    }

    void eventTriggerNewArticle()
    {
        cout << "The new article event is triggered." << "\n";
        notify_observers();
    }

int const get_Blog_id()
//int get_Blog_id()
{
return 21022015;
}
};

class User : public Observer
{
public:
    virtual void notify(Subject* s)
    {
        Blog *a;
        a = dynamic_cast<Blog*>(s);
       cout << a->get_Blog_id() << "\n";
    }
};

int main ()
{
    Blog newArticle = Blog();
    User u = User();
    newArticle.register_observer(&u);
    newArticle.eventTriggerNewArticle();
    return 0;
}
/*OUTPUT:
New Article Posted.
The new article event is triggered.
21022015
*/