【发布时间】:2015-11-04 01:17:30
【问题描述】:
我有以下代码:
class FooType1 : public FooInterface, public BarInterface1 {}
class FooType2 : public FooInterface, public BarInterface2 {}
class FooType3 : public FooInterface, public BarInterface3 {}
FooInterface service1 = boost::shared_ptr<FooType1>(new FooType1());
FooInterface service2 = boost::shared_ptr<FooType2>(new FooType2());
FooInterface service3 = boost::shared_ptr<FooType3>(new FooType3());
new Host(service1, service2, service3);
Host::Host(boost::shared_ptr<BarInterface1> service1,
boost::shared_ptr<BarInterface2> service2,
boost::shared_ptr<BarInterface3> service3) {
obj1 = service1;
obj2 = service2;
obj3 = service3;
}
我需要以类似于FooType1 到FooType3 的方式添加FooType4、FooType5 等。在Host 构造函数中,我必须将正确的服务分配给正确的对象(1 到 1、2 到 2 等)。鉴于我知道会添加许多新服务,我该如何正确封装呢?
我考虑了向量,因为在某些地方我必须对所有服务执行一些操作,因此“for each”循环会很有帮助。如何以合理的方式从 Host 构造函数的向量中获取对象?也许是一些设计模式?
【问题讨论】:
-
传入一个预先创建的向量。包括一个
AddService成员函数。选择最有意义的方式并使用它。 -
这听起来像是组合优于继承的情况。想想工厂模式什么的。
标签: c++ design-patterns architecture encapsulation