I am learning Prototype design pattern and I am little bit confused about main idea of this pattern and when to use it. Can you please help me to make clear some points for me?
1) If I am get right from this discussion, the main idea of Prototype pattern is saving cost of creating new object (NOTE this not mean memory allocating). Sometimes to create your object you need to request data from somewhere (for example DB request) or some big calculations and it might be time consuming so rather than to create new object it is more efficient to clone it. So the main idea of Prototype pattern is NOT saving efforts on memory allocation but on creating your object as it may be data driven or result of a calculation. Please correct me if I am wrong.
2) Is this code good example of prototype design pattern c++ implementation?
// 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;
}
Thanks in advance for your time and effort.
ID
Social Insurance Documents
This list can be quiet huge. To create account I have provided this data. So when after some time I will need some new account I DO NOT need to provide all this information. Bank can clone data. So the main target of prototype design pattern is saving cost of creating new Object. Hence the main idea of Prototype pattern is NOT saving efforts on memory allocation but on creating your object as it may be data driven or result of a calculation, or holding some stage information.