Design Pattern 6: Clever Implementation of factory

Source: Internet
Author: User

This article shows the implementation of a factory mode used in the actual project. When adding a new type to the system, you only need to change the implementation file of the new type, minimize the interference of New Types on application code.

The basic idea of this factory implementation is: inherit from the new type of the same interface and create its object through a function. The class constructor in C ++ will be automatically called, define a static (Auxiliary) class object in the implementation file of the new type. In the constructor of the helper class, register a new type of creation function with the factory Singleton.

Let's take a look at the code first and then explain it one by one. The following is the header file content of the command interface CommandObject:

class CommandObject{public:    CommandObject(){}    virtual ~CommandObject(){}    virtual void execute() = 0;};

CommandObject is a pure virtual class and serves as a public interface.

In the official system, I use the command mode to encapsulate specific operations and PASS command objects to some UI elements, such as buttons. When a UI element is triggered by a mouse or a key, the associated CommandObject is called to execute specific commands. For more information about the command mode, see design mode Introduction 3: command.

The following is the header file of the command object factory class:

#ifndef COMMANDOBJECTFACTORY_H#define COMMANDOBJECTFACTORY_H#include "commandObject.h"typedef CommandObject * (*LPFNCREATE)();class  CommandObjectFactory{    CommandObjectFactory(const CommandObjectFactory &);    CommandObjectFactory & operator=(const CommandObjectFactory &);    CommandObjectFactory();public:    ~CommandObjectFactory();    static CommandObjectFactory * instance();    CommandObject * commandObject(const char * szKeyword);    void regist(const char * szKeyword, LPFNCREATE lpfnCreate);private:    const char ** m_keywords;    LPFNCREATE * m_functions;    int m_iCount;    int m_iCursor;};#define EXPORT_COMMAND_CREATOR(KEYWORD, COMMANDCLASS) \    CommandObject * _command_object_creator_##KEYWORD() {\        return new COMMANDCLASS;\    }\    class Static##KEYWORD##PluginInstance{ \    public: \        Static##KEYWORD##PluginInstance(){ \            CommandObjectFactory::instance()->regist(#KEYWORD, _command_object_creator_##KEYWORD);\        }\    };\    static Static##KEYWORD##PluginInstance static##KEYWORD##Instance#endif // COMMANDOBJECTFACTORY_H

In this header file, the factory class CommandObjectFactory is defined. First, it is a singleton. This is the common practice. The factory class is implemented as a singleton. For more information about Singleton, see design patterns 2: Singleton.

CommandObjectFactory defines the factory method commandObject for object creation. It accepts a string as a keyword and internally creates a command object based on this keyword. A regist method is also defined to register the creation function of the command object with the factory. It is mainly used by the auxiliary macro EXPORT_COMMAND_CREATOR defined later to automatically register the creation function.

The macro EXPORT_COMMAND_CREATOR has two parameters: one is the key word that corresponds to the implementation class of a specific command object, and the other is the COMMANDCLASS Class Name of the command object class. This macro is very important. It helps us complete the registration of the created function, and limits the changes to the Code of the New Type in the implementation file of the new type, without any impact on the existing code.

After the macro EXPORT_COMMAND_CREATOR is expanded, the macro EXPORT_COMMAND_CREATOR is divided into several parts: the helper class declaration, the Global static helper class instance with the scope of the file, and the helper class constructor calls the CommandObjectFactory. It is also very simple to use, we will mention later.

The following is the implementation of CommandObjectFactory:

#include "commandObjectFactory.h"#include 
 
  #include 
  
   #include 
   
    using namespace std;#define INITIALISE_SIZE    32#define INCREMENT_SIZE     8static CommandObjectFactory * s_instance = 0;CommandObjectFactory::CommandObjectFactory()    : m_keywords(0)    , m_functions(0)    , m_iCount(0)    , m_iCursor(0){}CommandObjectFactory::~CommandObjectFactory(){}CommandObjectFactory * CommandObjectFactory::instance(){    if(!s_instance)    {        s_instance = new CommandObjectFactory;        cout << "CommandObjectFactory initialised" << endl;    }    return s_instance;}void CommandObjectFactory::regist(const char * szKeyword, LPFNCREATE lpfnCreate){    if(!szKeyword || !lpfnCreate) return;    //repeat check    for(int i = 0; i < m_iCursor; ++i)    {        if(!strcmp(m_keywords[i], szKeyword))            return ;    }    if(!m_functions)    {        m_functions = (LPFNCREATE*)calloc(INITIALISE_SIZE, sizeof(LPFNCREATE));        m_keywords = (const char**)calloc(INITIALISE_SIZE, sizeof(char*));        m_iCount = INITIALISE_SIZE;        m_iCursor = 0;    }    else if( m_iCursor == m_iCount )    {        m_iCount += INCREMENT_SIZE;        m_functions = (LPFNCREATE*)realloc( m_functions, m_iCount * sizeof(LPFNCREATE) );        m_keywords = (const char**)realloc( m_keywords, m_iCount * sizeof(char*));    }    m_keywords[m_iCursor] = (const char *)strdup(szKeyword);    m_functions[m_iCursor] = lpfnCreate;    m_iCursor++;    cout << "register create function for - " << szKeyword << endl;}CommandObject * CommandObjectFactory::commandObject(const char * szKeyword){    for(int i = 0; i < m_iCursor; ++i)    {        if(!strcmp(m_keywords[i], szKeyword))        {            return m_functions[i]();        }    }    cout << "no create function for - " << szKeyword << endl;    return 0;}
   
  
 

The implementation is relatively simple. We maintain two arrays in CommandObjectFactory to store the keywords and create functions for the command objects respectively. The two correspond one to one, and regist () function Maintenance creates function registration and dynamic growth of internal arrays. The commandObject () function compares strings in the internal Array Based on the input keyword szKeyword. After matching the keywords, locate the corresponding creation function to create a command object.

The following describes how to implement the specific command object class and how to automatically register the macro EXPORT_COMMAND_CREATOR. Code:

class ShutdownCommand : public CommandObject{public:    void execute()    {        cout << endl << "ShutdownCommand::execute" << endl;    }};EXPORT_COMMAND_CREATOR(shutdown, ShutdownCommand);class RebootCommand : public CommandObject{public:    void execute()    {        cout << endl << "RebootCommand::execute" << endl;    }};EXPORT_COMMAND_CREATOR(reboot, RebootCommand);

Everything is intuitive and needless to say.

The following is the main () function to see how to use the command object factory to create the desired command object:

int main(){    CommandObject * cmd = CommandObjectFactory::instance()->commandObject("shutdown");    cmd->execute();    return 0;}

It is very simple and does not need to be explained. The following is the execution result of the program:


Well, so far, a simple and easy-to-use simple factory model has been introduced, so that I can better understand the Implementation ideas. In actual projects, A little more complicated.

Review:

    One of the design patterns: Overview of design patterns 2: Singleton design patterns 3: command design patterns 4: Template Methods) 5. Introduction to Pattern Design: factory)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.