Home > Mobile >  C return new instance of object from dictionary
C return new instance of object from dictionary

Time:12-21

How to achieve something like this in C ? I'd like some method to return instances of object based on provided string. I suspect map might be solution but I don't know how to pass method to it?

class Container {
  dictionary = {
    A: () => new A(),
    B: () => new B(),
    C: () => new C(),
  };

  method(choice: string): Parent {
    return this.dictionary[choice];
  }
}

class Parent {}

class A extends Parent {}

class B extends Parent {}

class C extends Parent {}

CodePudding user response:

I can propose the following solution:

a base class:

class Base {
}

a factory singleton:

class Factory
{
public:
    static Factory &instance()
    {
        static Factory inst;
        return inst;
    }
    bool Register(const std::string &name, CreateCallback funcCreate)
    {
        m_classes.insert(std::make_pair(name, funcCreate));    
    }
    Base* CreateInstance(const std::string &name)
    {
        auto it = m_classes.find(name);
        if(it != m_classes.end())
        {
            return it->second();
        }

    return nullptr;
    }

private:
    using CreateCallback = Base *(*)();
    std::map<std::string, CreateCallback> m_classes;
}

#define CLASS_IMPL(T) Base *T::CreateMethod() { return new T(); }

#define REGISTER_CLASS(T,N) bool T::m_registered = Factory::instance().Register(N, &T::CreateMethod);\
CLASS_IMPL(T)

#define CLASS_DECL protected: \
static Base *CreateMethod(); \
static bool m_registered; \

usage: class declaration:

class A: public Base
{
BASE_DECL
public:
    A(){}
}

class definition:

REGISTER_CLASS(A, "A");
A::A() : Base()
{
}

create other classes in such manner.

usage:

Base* a = Factory::Instance().CreateInstance("A");

This is Factory implementation and so a kind of a "self registration" pattern.

  •  Tags:  
  • c
  • Related