【问题标题】:Class encapsulation: how to prepare code for adding new classes?类封装:如何准备添加新类的代码?
【发布时间】: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;
}

我需要以类似于FooType1FooType3 的方式添加FooType4FooType5 等。在Host 构造函数中,我必须将正确的服务分配给正确的对象(1 到 1、2 到 2 等)。鉴于我知道会添加许多新服务,我该如何正确封装呢?

我考虑了向量,因为在某些地方我必须对所有服务执行一些操作,因此“for each”循环会很有帮助。如何以合理的方式从 Host 构造函数的向量中获取对象?也许是一些设计模式?

【问题讨论】:

  • 传入一个预先创建的向量。包括一个AddService 成员函数。选择最有意义的方式并使用它。
  • 这听起来像是组合优于继承的情况。想想工厂模式什么的。

标签: c++ design-patterns architecture encapsulation


【解决方案1】:

你说,

我需要添加FooType4,FooType5, etc. in a way analogoues toFooType1throughFooType3. In theHost`构造函数我必须将正确的服务分配给正确的对象(1到1、2到2等)。鉴于我知道会添加许多新服务,我该如何正确封装呢?

鉴于此,您的方法不正确。如果您还没有阅读过Open/Closed Prinicple,我强烈建议您阅读。

更好的方法可能是允许客户将服务添加到Host。这就是我的想法。

class Host
{
   public:
      void addService(std::shared_ptr<FooInterface> service)
      {
         services_.push_back(service);
      }

   private:
      std::vector<std::shared_ptr<FooInterface>> service_;
};

并将其用作:

Host* host = new Host(service1, service2, service3);
host->addService(std::shared_ptr<FooInterface>(new FooType1()));
host->addService(std::shared_ptr<FooInterface>(new FooType2()));
host->addService(std::shared_ptr<FooInterface>(new FooType3()));

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多