c++ - 类封装 : how to prepare code for adding new classes?

标签 c++ design-patterns architecture encapsulation

我有以下代码:

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;
}

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

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

最佳答案

你说,

I need to add FooType4,FooType5, etc. in a way analogoues toFooType1throughFooType3. In theHost` constructor I have to assign the proper service to the proper object (1 to 1, 2 to 2, etc.). Given that I know there will be many new services added, how can I properly encapsulate this?

鉴于此,您的方法不正确。如果您还没有阅读 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()));

关于c++ - 类封装 : how to prepare code for adding new classes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31948126/

相关文章:

c++ - 如何检查从键盘输入的特定整数值是否存在于 C++ 文件的一行或多行中

design-patterns - 什么是具有出色设计的小型开源项目?

architecture - 您现在正在做MDA(模型驱动的体系结构)吗?如果是这样,您将使用哪些工具,其工作方式如何?

c++ - 如何在 Windbg 的析构函数中设置断点?

c++ - 长与。诠释 C/C++ - 有什么意义?

c++ - 如何通过聚合初始化来初始化自定义数组类?

c# - .NET 中是否有包含单个 EventHandler 的标准接口(interface)

c# - 如何首先在 EF 代码中处理一个数据库在多个数据库上下文中使用的一个类?

.net - 避免大量传播暴露给 ViewModel 的属性和事件

c# - 用户的账户余额应该存储在数据库中还是动态计算?