Click here to Skip to main content
Click here to Skip to main content

Factory class with Open Closed Principle

By , 30 Apr 2013
 

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

  • 30 Apr 2013: Initial revision.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Manish K. Agarwal
Team Leader Pitney Bowes
India India
Member
Working with Pitney Bowes, Noida (India). Using C/C++, VC++, MFC, STL, C#, Java etc. on various platform like Windows, Unix, Macintosh etc. from last 12 years to convert various type of requirements into running software components. My core expertise is multithreaded desktop product development on Windows.

Comments and Discussions

Comment 5 messages have been posted for this article Visit http://www.codeproject.com/Tips/584646/Factory-class-with-Open-Closed-Principle to post and view comments on this article, or click here to get a print view with messages.

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130513.1 | Last Updated 30 Apr 2013
Article Copyright 2013 by Manish K. Agarwal
Everything else Copyright © CodeProject, 1999-2013
Terms of Use