如何实现“注册模式”?在C ++中,使用单个注册表进行许多接口实现 [英] How to implement "Registry pattern" in C++, using single registry for many interface implementation
问题描述
让一个虚拟纯类 Interface 和两个具体的实现 InterfaceImplA 和 InterfaceImplB 。
Let a virtual pure class Interface and two concrete implementation InterfaceImplA and InterfaceImplB.
我想拥有一个注册表,可以在其中注册 Interface 的各种实现。该注册表必须能够使用任意标识符(QString,std :: string ..)创建具体类型的实例。
I want to have a registry where i can register various implementations of Interface. This registry must be able to create instances of my concrete types, using an arbitrary identifier (QString, std::string..).
示例应用程序如下:
Registry<Interface> registry;
registry.register<InterfaceImplA>("A");
registry.register<InterfaceImplB>("B");
InterfaceImplA* instanceA = registry.create("A");
InterfaceImplB* instanceB = registry.create("B");
它将用作数据模型序列化/反序列化组件的一部分,其中序列化的对象使用
It will be used as as part of a data model serialisation/deserialization component, where the serialized object uses only the interface, but serialized instances may use various implementation.
推荐答案
/*!
*
* \brief Allow to implement the Registry pattern applied to interface implementation
*
* A registry is needed for each implemented interface. Then, implementation are
* registered into it, using arbitrary string as identifier. Once registered, the
* registry is able to provide a concrete instance of a type, given is string identifier.
*
*/
template <class InterfaceType, class IdType = std::string>
class ImplementationRegistry
{
typedef boost::function0<InterfaceType *> Creator;
typedef std::map<IdType, Creator> Creators;
Creators m_Creators;
public:
/*!
*
* \brief Register a new concrete type, indexed with given identifier
*
* \note the concrete type must be a specialized type of the interface
* managed by the registry.
*/
template <class ConcreteType>
void Register(const IdType &identifier)
{
ConstructorWrapper<ConcreteType> wrapper;
Creator creator = wrapper;
m_Creators[identifier] = creator;
}
/*!
*
* \brief return a concrete implementation og the managed interface according to an identifier
*
* \return an implementation or null in the identifier is unknown
*/
InterfaceType *Create(const IdType &identifier)
{
InterfaceType *result = nullptr;
auto it = m_Creators.find(identifier);
if (it != m_Creators.end())
{
result = it->second();
}
return result;
}
protected:
template<class ConcreteType>
struct ConstructorWrapper
{
InterfaceType *operator()() const { return new ConcreteType(); }
};
};
}
这篇关于如何实现“注册模式”?在C ++中,使用单个注册表进行许多接口实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!