工厂构造函数中的智能指针似乎强制创建的对象知道它是如何使用的



我使用工厂在运行时根据一些用户选择创建一些对象。

所以我现在有这样的东西:

class UpdateServiceFactory{
public:
std::unique_ptr<UpdateService> create(Widget widget){
if(widget.name == "name one"){
auto dependency = std::make_unique<ChildDependency>();
return std::make_unique<ChildUpdateService>(std::move(dep));
}
}
}

我的儿童更新服务可以:

a( 取一个指向其CCD_ 1的唯一指针。一方面,这似乎很理想,因为我希望当我的UpdateService被破坏时,我的dependency超出范围。但另一方面,我现在从一个不应该真正关心它的对象中强制对对象的创建者执行终身策略,只是为了方便清理内存。例如,我的ChildUpdateService不知道工厂是否也想将它刚刚创建的相同依赖项传递给另一个类,而唯一的指针会使这变得不可能。现在,我似乎已经通过在构造函数上指定智能指针来规定了这一点。

b( 我可以将一个原始的dependency指针带到ChildUpdateService的构造函数中,并使用unique_ptr::get传递它。但现在我有一个问题,需要在其他地方管理dependency指针的生存期。某些东西必须拥有它,否则一旦create函数返回,它就会超出范围。在这一点上,唯一知道指针的对象是我的工厂,但工厂也不应该真正负责管理指针的生命周期。它的工作就是创建对象,就这样。我觉得再做任何事情都会违反SRP。

所以我想我的问题有两个方面。1( 如果构造函数采用了一个唯一的指针,那么我是否在为不应该成为的对象的创建者制定终身策略?2(有没有一种模式可以解决这个问题,我可以(应该(使用它,比如创建一个中间对象,它的工作是管理依赖关系的生存期?

如果您希望您的服务类型决定这一点,那么在创建依赖关系时需要它的帮助。你可以这样做:

class ServiceBase { // you need this anyway
public:
virtual ~ServiceBase() {}
};
class ChildUpdateService : public ServiceBase {
private:
// now, the class itself defines that it wants to store a unique_ptr.
// not the generic factory!
ChildUpdateService(std::unique_ptr<ChildDependency>);
public:
template <typename Dep, typename... Args>
static std::unique_ptr<ChildUpdateService> make(Args&&... args) {
return std::make_unique<ChildUpdateService>(std::make_unique<T>(std::forward<Args>(args)...));
}
};

如果您有几个这样的服务,可以创建一个使用CRTP的中间类模板。

这意味着您的通用工厂不必决定相应的服务实现如何保持其依赖性(如unique_ptr、shared_ptr、自动成员等(

class UpdateServiceFactory {
public:
std::unique_ptr<UpdateService> create(Widget widget) {
if (widget.name == "name one")
return ChildUpdateService::make<ChildDependency>();
}
}

最新更新