c++ - 扩展此 C++ 工厂实现的最佳方法?

标签 c++ design-patterns factory

我想扩展现有的一段代码,但我不确定这样做的最简洁的设计方法。我想知道现有设计是否真的支持我正在考虑的那种扩展。

有一个看起来像这样的工厂:

class XYZFactory
{
public:
  static XYZFactory& getDefaultInstance() // so this is a singleton!
  // ... some create methods
  // std::unique_ptr<ABC> createABC();
private:
  std::unique_ptr<XYZFactoryImpl> m_impl;
}
---
XYZFactory::XYZFactory() : m_impl(std::make_unique<XYZImpl>;

现在的问题是我想通过派生 XYZImpl 来扩展它的功能。但是,我想避免在工厂类中公开该实现细节,例如添加一个单独的 XYZFactory 构造函数,并将 ExtendedXYZImpl 作为参数来注入(inject)该扩展。

为澄清而添加/编辑:我应该调用 XYZImpl XYZFactoryImpl。它执行实际的对象创建。 XYZFactory 将 createWhatever() 调用传递给它。 m_Impl 中只有一个 XYZImpl 实例。 我真正希望能够动态更改的是用于对象创建的 XYZImpl m_ABC(ABC 的实例)的成员。我想从 ABC 派生。

从 XYZFactory 中取消单例设计和子类化会有帮助吗?

有什么想法吗?

谢谢!

标记

最佳答案

XYZFactory 目前对 XYZFactoryImpl 有依赖性,因此很明显,如果不在 上公开该功能,就无法注入(inject)对 ExtendedXYZImpl 的依赖性>XYZ 工厂。如果这是 Not Acceptable ,唯一的选择就是放弃当前的 XYZFactory 设计。

您的问题中没有太多的限制条件可供我们用来形成答案,但我建议您首先将 XYZFactory 设为抽象工厂:

class XYZFactory {
public:
  virtual ~XYZFactory(){}
  virtual std::unique_ptr<ABC> createABC() const = 0;
}

有两个实现:

class XYZFactoryImpl : public XYZFactory {
public:
  std::unique_ptr<ABC> createABC() const override {
    return std::make_unique<ABC>();
  }
};

class ExtendedXYZFactoryImpl : public XYZFactory {
public:
  std::unique_ptr<ABC> createABC() const override {
    return std::make_unique<DerivedABC>();
  }
};

然后,您可以提供一个函数来获取单例实例,并提供一种重新安置不同单例实例的方法。例如:

namespace details {  
  // Or this could be hidden in an anonymous namespace in a .cpp file
  std::unique_ptr<XYZFactory>& getXYZFactoryInstanceMutable() {
    static std::unique_ptr<XYZFactory> singleton = std::make_unique<XYZFactoryImpl>();
    return singleton;
  }
}

const XYZFactory& getXYZFactoryInstance() {
  auto& singleton = details::getXYZFactoryInstanceMutable();
  if (!singleton)
      throw std::runtime_error("No XYZFactory registered");
  return *singleton;
}

void setXYZFactoryInstance(std::unique_ptr<XYZFactory> new_factory) {
  details::getXYZFactoryInstanceMutable() = std::move(new_factory);
}

然后注入(inject)你的 ExtendedXYZFactoryImpl 你可以这样做:

setXYZFactoryInstance(std::make_unique<ExtendedXYZFactoryImpl>());

auto abc = getXYZFactoryInstance().createABC();

Live demo .

关于c++ - 扩展此 C++ 工厂实现的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37021652/

相关文章:

c++ - 使用 C++ 在 OpenCV 中矩阵中的多维数据

c++ - 使用委托(delegate)调用构造函数和另一个构造函数体的区别

C++ 将子子类转换为基类

angularjs - 为什么工厂在使用 $http.get 时优先提供服务

php - 工厂方法可能违反 Demeter 法则?

c++ - golang : call C++ code in cross platform

c++ - 纯虚拟方法 VS。函数指针

javascript - 抽象 jQuery

oop - 确保在方法 B 之前调用方法 A 的设计模式

constructor - 如何使用工厂常量构造函数?