抽象工厂改进
Abstract Factory Improvements
编辑:我决定为未来的读者编辑这篇文章。简而言之,它显示了在模板列表中调用模板类型构造函数的可接受方法。例如,以下内容:
int main()
{
unique_ptr<factory> real_widget_factory(new widget_factory(5.0, 6.0));
}
而不仅仅是局限于:
unique_ptr<factory> real_widget_factory(new widget_factory()); // empty
该标准提供了您需要的所有必要基础设施。您可以删除所有这些代码。
template<typename T, typename... Args> std::unique_ptr<T> make_unique(Args&&... args) {
return std::unique_ptr<T>(std::forward<Args>(args)...);
}
struct train_factory {
train_factory(std::function<std::unique_ptr<locomotive>()> ml,
std::function<std::unique_ptr<freight_car>()> mc)
: make_locomotive(std::move(ml)),
, make_car(std::move(mc)) {}
std::function<std::unique_ptr<locomotive>()> make_locomotive;
std::function<std::unique_ptr<freight_car>()> make_car;
};
train_factory make_concrete_factory(double x1, double x2) {
return train_factory(
[=] { return make_unique<real_locomotive>(x1); },
[=] { return make_unique<real_car>(x2); }
);
}
int main() {
auto fact = make_concrete_factory(1.0);
auto loc = fact.make_locomotive();
}
这似乎可以满足您的所有要求。在这种情况下,函数具有绑定到工厂的参数(并且此绑定是任意的)。当然,如果您愿意,您也可以修改函数以接受参数,或者以任意方式和组合使用两者。
struct train_factory {
std::function<std::unique_ptr<locomotive>(double)> make_locomotive;
std::function<std::unique_ptr<freight_car>(double)> make_car;
};
train_factory make_concrete_factory() {
return train_factory {
[](double x1) { return make_unique<real_locomotive>(x1); },
[](double x2) { return make_unique<real_car>(x2); }
};
}
int main() {
auto fact = make_concrete_factory();
auto loc = fact.make_locomotive(1.0);
}
相关文章:
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 抽象工厂结构的差异
- 下面抽象工厂设计模式的实现是正确的吗
- 工厂方法模式使用继承而抽象工厂模式使用组合如何
- 使用空基类强制继承抽象工厂的做法是不好的吗?
- 具有抽象工厂的派生类的 C++11 单例
- 用于抽象基类和派生类的工厂功能的C 返回类型
- 抽象工厂改进
- 为工厂创建一个抽象工厂是否有意义
- 抽象工厂模式客户端代码
- C++抽象工厂是否应该为构造对象提供销毁方法
- 链接自注册的抽象工厂
- 抽象工厂的多重继承
- 在C++中实现抽象工厂 PIMPL 习语的运行时错误
- 克隆智能指针vs抽象工厂
- 抽象工厂类中的细微设计错误
- 使用抽象工厂和模板元编程的可扩展架构
- 带有参数化构造函数的抽象工厂
- 抽象工厂设计模式在c++中的应用
- 模板类困境的抽象工厂