C++类模板实现工厂模式(优化if else/switch case)

寻技术 C/C++编程 2023年07月11日 114

引自: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")};

 

关闭

用微信“扫一扫”