我需要获取一些抽象类型的新实例,我想到的两件事是抽象工厂和克隆智能指针。哪个更好看?工厂方法似乎更通用,但过于冗长,尤其是当抽象对象嵌套时。克隆指针更紧凑,但看起来有点难看,因为我们需要创建一个“虚拟”对象用作模板来创建其他对象。
class IObject {
public:
virtual ~IObject() {}
};
class Foo: public IObject {
public:
struct Config {};
explicit Foo(const Config& config): config_(config) {}
private:
Config config_;
};
抽象工厂:
class IObjectFactory {
public:
virtual ~IObjectFactory() {}
virtual std::unique_ptr<IObject> Create() const = 0;
};
class FooFactory: public IObjectFactory {
public:
explicit FooFactory(const Foo::Config& config): config_(config) {}
std::unique_ptr<IObject> Create() const {
return std::unique_ptr<IObject>(new Foo(config_));
}
private:
Foo::Config config_;
};
void DoSomething(const std::shared_ptr<IObjectFactory>& factory) {
std::vector<std::shared_ptr<IObject>> objects;
for (int i = 0; i < 10; ++i) {
objects.push_back(factory->Create());
}
// Do something with the created objects
}
int main() {
auto factory = std::make_shared<FooFactory>(Foo::Config());
DoSomething(factory);
}
克隆指针(实现之一):
template <typename T> class clone_ptr; // deep cloning smart pointer
void DoSomething(const clone_ptr<IObject>& object) {
std::vector<clone_ptr<IObject>> objects;
for (int i = 0; i < 10; ++i) {
objects.push_back(object);
}
// Do something with the created objects
}
int main() {
clone_ptr<IObject> object(new Foo(Foo::Config()));
DoSomething(object);
}