虚拟构造函数成语和工厂设计

Sac*_*ach 3 c++ design-patterns virtual-functions

在虚拟构造函数中,有虚函数,它使用虚函数返回对象的新对象或副本.但是,要以多态方式调用这些虚函数,必须使用实际构造函数创建该类的对象.

在设计模式上下文中,它意味着在使用多态对象创建方式之前,客户端是否知道对象的类型?

Ker*_* SB 5

客户不一定要了解具体类型.例如,考虑以下层次结构:

struct Base
{
    virtual ~Base();
    virtual Base * clone() const = 0;
    static Base * create(std::string const &);
    // ...
};

struct A : Base { A * clone() const { return new A(*this); } /* ... */ };
struct B : Base { B * clone() const { return new B(*this); } /* ... */ };
struct C : Base { C * clone() const { return new C(*this); } /* ... */ };

Base * Base::create(std::string const & id)
{
    if (id == "MakeA") return new A;
    else return new C;
};
Run Code Online (Sandbox Code Playgroud)

在这种情况下,客户端可以制作和复制现有对象,如下所示:

Base * p = Base::create("IWantB");  // or std::unique_ptr<Base> !
Base * q = p->clone();
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,客户端都不知道*por 的动态类型*q.