I was checking the factory design pattern in c++. I understood why we use the cloning method:
Although genetic factories producing clones of the universal soldier are quite a scary prospect, cloning C objects is a harmless and useful activity most of the time. Here the goal is slightly different from what we dealt with so far: We don’t have to create objects from scratch anymore. We have a pointer to a polymorphic object, and we’d like to create an exact copy of it. Because we don’t exactly know the type of the polymorphic object, we don’t exactly know what new object to create, and this is the actual issue. Quote
The part that I didn't understand is return new Line(*this);
in function virtual Line* Clone() const
. Can you please tell me If my interpretation is correct.
- In
Shape* Create(const std::string& key) const
we calltmp=((*it).second)->Clone();
- Since we want an exact copy, what we did in here is call the copy constructor
Line(const Line &)
and pass this as argument. But sincethis
a pointer we have to dereference it because we are passing it by reference to the copy constructor. - Suppose we use
return new Line()
instead ofreturn new Line(*this)
what will happen? we wont be returning a copy of the object but a new object? which is kind of stupid and wrong. Why create a new object since it already exists
public:
virtual Shape* Clone() const = 0;
...
};
class Line : public Shape
{
public:
virtual Line* Clone() const
{
return new Line(*this);
}
...
};
//The create function is from the Factory
Shape* Create(const std::string& key) const
{
Figure* tmp=0;
std::map<string, Figure*>::const_iterator it=m_map.find(key);
if(it!=m_map.end())
{
tmp=((*it).second)->Clone();
}
return tmp;
}