虚拟构造器成语和工厂设计 [英] Virtual constructor idiom and factory design
问题描述
在设计模式上下文中,这意味着客户端知道该类型使用对象创建的多态方式之前的对象?
客户端不一定必须了解具体的类型。例如,考虑这个层次结构:
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 C;
};
在这种情况下,客户端可以制作和复制现有对象,如下所示:
Base * p = Base :: create(IWantB); //或std :: unique_ptr< Base> !
Base * q = p-> clone();
在这两种情况下,客户端都不知道动态类型 * p
或 * q
。
In virtual constructor idiom there are virtual functions which returns new object OR copy of the object using virtual functions. But then to call these virtual functions polymorphic way, you must have object of that class created using actual constructor.
In design pattern context, it means client is aware of the type of object before using polymorphic way of object creation?
The client doesn't necessarily have to be aware of the concrete type. For example, consider this hierarchy:
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;
};
In this case, the client can make and copy an existing object like so:
Base * p = Base::create("IWantB"); // or std::unique_ptr<Base> !
Base * q = p->clone();
In neither case does the client ever know the dynamic type of *p
or *q
.
这篇关于虚拟构造器成语和工厂设计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!