【问题标题】:When to use Prototype design pattern何时使用原型设计模式
【发布时间】:2015-10-12 14:29:48
【问题描述】:

我正在学习原型设计模式,我对这种模式的主要思想以及何时使用它有点困惑。 你能帮我澄清一些观点吗?

1) 如果我从这个discussion 中得到正确的答案,原型模式的主要思想是节省创建新对象的成本(注意这并不意味着内存分配)。有时要创建您的对象,您需要从某个地方请求数据(例如数据库请求)或一些大型计算,这可能很耗时,因此与其创建新对象相比,克隆它更有效。所以原型模式的主要思想不是节省内存分配的工作,而是创建你的对象,因为它可能是数据驱动的或计算的结果。 如果我错了,请纠正我。

2) 这段代码是原型设计模式 c++ 实现的好例子吗?

// Prototype
class Prototype
{
public:
    virtual ~Prototype() { }
    virtual Prototype* clone() const = 0;
};

// Concrete prototype
class ConcretePrototype : public Prototype
{
private:
    int m_x;
public:
    ConcretePrototype(int x) : m_x(x) { }
    ConcretePrototype(const ConcretePrototype& p) : m_x(p.m_x) { }
    virtual Prototype* clone() const
    {
       return new ConcretePrototype(*this);
    }

    void setX(int x) { m_x = x; }     
    int getX() const { return m_x; }
    void printX() const { std::cout << "Value :" << m_x << std::endl; }
};

// Client code
void prototype_test()
{
    Prototype* prototype = new ConcretePrototype(1000);
    for (int i = 1; i < 10; i++) {
       ConcretePrototype* tempotype =
            dynamic_cast<ConcretePrototype*>(prototype->clone());
        tempotype->setX(tempotype->getX() * i);
        tempotype->printX();
        delete tempotype;
    }
    delete prototype;
}

提前感谢您的时间和精力。

【问题讨论】:

  • 第二个问题的代码目前有效,您正在寻求有关它的反馈。一般来说,这些问题对于这个网站来说太固执了,但你可能会在CodeReview.SE 找到更好的运气。记得阅读their question requirements,因为他们比这个网站更严格。
  • 你的第一点是正确的。

标签: design-patterns prototype-pattern


【解决方案1】:
  1. 经过调查,我想介绍一些原型设计模式的真实示例。 假设我是一家银行的客户。要在那里开户,我需要提供一些文件。

身份证

社会保险文件

这个列表可能非常庞大。为了创建帐户,我提供了这些数据。因此,当一段时间后我需要一些新帐户时,我不需要需要提供所有这些信息。银行可以克隆数据。 所以原型设计模式的主要目标是节省创建新对象的成本。因此,原型模式的主要思想不是节省内存分配,而是创建对象,因为它可能是数据驱动的或计算的结果,或者保存一些阶段信息。

  1. 提供的代码可以被视为原型设计模式实现的示例,因为最重要的部分是状态的复制,并且在这里使用复制 CTOR 是有意义的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-25
    • 1970-01-01
    • 2012-12-02
    • 2016-03-25
    • 1970-01-01
    • 2015-06-29
    • 1970-01-01
    相关资源
    最近更新 更多