引自:https://blog.csdn.net/weixin_43795921/article/details/127224633
template <typename IdentifierType, class AbstractProduct,
class ProductCreator = AbstractProduct *(*)(),
class MapContainer = std::map<IdentifierType, ProductCreator>>
class Factory {
public:
bool Register(const IdentifierType &id, ProductCreator creator) {
return producers_.insert(std::make_pair(id, creator)).second;
}
bool Unregister(const IdentifierType &id) {
return producers_.erase(id) == 1;
}
void Clear() { producers_.clear(); }
bool Empty() const { return producers_.empty(); }
template <typename... Args>
std::unique_ptr<AbstractProduct> CreateObjectOrNull(const IdentifierType &id,
Args &&... args) {
auto id_iter = producers_.find(id);
if (id_iter != producers_.end()) {
return std::unique_ptr<AbstractProduct>(
(id_iter->second)(std::forward<Args>(args)...));
}
return nullptr;
}
template <typename... Args>
std::unique_ptr<AbstractProduct> CreateObject(const IdentifierType &id,
Args &&... args) {
auto result = CreateObjectOrNull(id, std::forward<Args>(args)...);
PUB_E_IF(!result, "Factory could not create Object of type : " << id);
return result;
}
private:
MapContainer producers_;
};
Factory<int, IShape> oFactory;
oFactory.Register(1, []()->IShape*{return new CircleShape("color")};文章来源:https://www.toymoban.com/news/detail-541430.html
文章来源地址https://www.toymoban.com/news/detail-541430.html
到了这里,关于C++类模板实现工厂模式(优化if else/switch case)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!