当程序中许多的类需要使用共同的接口时,可以考虑工厂模式。传统的抽象工厂实现先定义用于创建不同产品的接口, 但将实际的创建工作留给了派生的具体工厂类。 每个工厂类型都对应派生出的不同产品。本文的工厂模式可以实现不同抽象工厂的异类集合,避免了定义多个工厂类。并且可以传递不同参数来构造生产不同类型的产品。
#include <memory>
#include <map>
#include <unordered_map>
#include <iostream>
template<typename AbsProduct, typename ProductKey=std::string, typename...Args>
class Factory {
public:
static Factory &GetInstance() {
static Factory factory;
return factory;
}
template<typename Product>
void Register(const ProductKey& key) {
factory_map_.emplace(key, [](Args...args)->AbsProduct*{
return new Product(args...);});
}
std::shared_ptr