What is the difference between prototype design pattern and copy constructor in C ++

I am trying to figure out when I should use the Prototype design template. Here is an example prototype, as I understand it:

class Prototype { public: virtual Prototype* clone() = 0; ... }; class ConcretePrototype : public Prototype { public: Prototype* clone() override { ... } }; // Usage: ConcretePrototype proto; auto protPtr = proto.clone(); 

Where is the question: Why is it better than:

 class Obj { public: Obj(); Obj(const Obj&); Obj& operator = (const Obj& other); }; Obj o; Obj o2 = o; 

So when should I really use Prototype?

+6
source share
2 answers

The copy constructor is an element of the language.

A prototype is a design pattern used to create (polymorphic) objects based on some existing instance.

It would be difficult to use the former to implement the latter, since the copy constructor is intended to be used when knowing the exact instance of the object, while the prototype is used when there may be some possible implementation of an interface, and you just want to get a new object of exactly the same implementation without resorting to some strange casting and checking methods.

Suppose you have interface I and implementations A and B At some point, you are given an object I that implements I You may not want to modify it, instead you prefer to get a new instance, and then make some changes to it. How can this be achieved if you do not know the exact class I ? The prototype template is one of the solutions to this problem: I* i2 = i.clone(); .

+9
source

Here is the link from the GoF book:

customers who clone a prototype should not be aware of their specific subclasses. Clients never need to lower the Clone return value to the desired type.

Prototype Design Pattern Example

For example, the client does NOT know (or cannot access) ConcretePrototype .

 // Usage: SomeMethod(PrototypeInterface iproto) // Thanks Prototype pattern { // ConcretePrototype proto; auto protPtr = iproto.clone(); // Gets correct object without calling concrete object constructor explicitly. } 

I hope you understand the situation when this template is useful. Also remember that there is no virtual constructor .

+5
source

All Articles