實現一個通用的工廠模板,支持產品註冊、註銷、創建,並可自定義錯誤處理策略。
#ifndef TEMPLATE_H
#define TEMPLATE_H
#include <map>
template
<
class AbstractProduct,
typename IdentifierType,
class ProductCreator = AbstractProduct*(*)(),
template <typename, class> class FactoryErrorPolicy = DefaultFactoryError
>
class Factory {
public:
bool Register(const IdentifierType& id, ProductCreator creator) {
return associations_.insert(AssocMap::value_type(id, creator)).second;
}
bool UnRegister(const IdentifierType& id) {
return associations_.erase(id) == 1;
}
AbstractProduct* CreateObject(const IdentifierType& id) {
typename AssocMap::const_iterator i = associations_.find(id);
if (i != associations_.end()) return (i->second)();
return OnUnknownType(id);
}
private:
typedef std::map<IdentifierType, ProductCreator> AssocMap;
AssocMap associations_;
};
template <class IdentifierType, class ProductType>
class DefaultFactoryError {
public:
class Exception : public std::exception {
public:
Exception(const IdentifierType& unknownId) : unknownId_(unknownId) {}
virtual const char* what() { return "unknown object type passed to Factory"; }
const IdentifierType GetId() { return unknownId_; }
private:
IdentifierType unknownId_;
};
protected:
static ProductType* OnUnknownType(const IdentifierType& id) {
throw Exception(id);
}
};
#endif