虚拟构造器成语和工厂设计 [英] Virtual constructor idiom and factory design

查看:170
本文介绍了虚拟构造器成语和工厂设计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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

解决方案

客户端不一定必须了解具体的类型。例如,考虑这个层次结构:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆