【发布时间】: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