Click here to Skip to main content
Full site     10M members (39.4K online)    

Factory class with Open Closed Principle

Introduction

This is to demonstrate a simple template based factory class which can be used as a generic class satisfying the concept of Open Closed Principle (OCP). There could be many enhancements but to get the idea straight, I am keeping it simple. Nothing much to write, the code speaks itself.

Using the code

The BaseFactory class is the main class to demonstrate the above idea. A specialized type of factory instance for some Product type hierarchy can be created as below:

BaseFactory<Product> productFactory;

To register a new Product type:

productFactory.RegisterType<P1>("P1");

To create instance of a Product type:

Product* product = productFactory.CreateInstance("P1");

Below is the complete implementation for the BaseFactory class:

// Base template Factory class

template<class T>
class BaseFactory
{
public:
    T *CreateInstance(std::string typeName)
    {
        TypeMap::iterator it = mTypeMap.find(typeName); 

        if ( it != mTypeMap.end())
        {
            return it->second();
        }
 
        return NULL;
    } 
 
    template<class DerivedT> 
   
    void RegisterType(std::string derivedTypeName)
    {
        this->mTypeMap[derivedTypeName] = &BaseFactory<T>::CreateT<DerivedT>;
    }

private:
    typedef std::map<std::string, T *(*)()> TypeMap;
    TypeMap mTypeMap;
    template<class DerivedT>
    static T* CreateT() { return new DerivedT; }
};

History

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search 
Per page   
QuestionI’m a bit confused.
George Swan
30 Apr '13 - 20:19 
AnswerRe: I’m a bit confused.
Manish K. Agarwal
1 May '13 - 1:45 
QuestionVery Nice
John Bandela
30 Apr '13 - 4:51 
AnswerRe: Very Nice
Manish K. Agarwal
30 Apr '13 - 6:39 
GeneralMy vote of 5
jsolutions_uk
30 Apr '13 - 0:46 

Last Updated 30 Apr 2013 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2013