Why Prototype isn't based on inherience?

RareScrap 1 year ago updated by Alexander Shvets 1 year ago 1

From the Prototype pattern page:

> Prototype isn’t based on inheritance, so it doesn’t have its drawbacks. On the other hand, Prototype requires a complicated initialization of the cloned object. Factory Method is based on inheritance but doesn’t require an initialization step.

I don't understand where exactly this pattern doesn't use inheritance. To summarize, you have several approaches how to implement this pattern:
1. Declare a copy() method somewhere in your base class
2. Create an interface with clone() method and implement it in your class hierarchy
3. Use copy constructor

The main idea of the Prototype pattern is keep copying mechanism inside classes rather than let the client code to copy object “from the outside”. So in order to perform copying, subclasses use the copy() method implementation of parent class to be able to correct clone private field. Then subclasses modify/pass to copy constructor the object received from the super.copy() implementation to initialize fields that subclass has access to. This mechanism clearly use the inheritance.

So how does the Prototype inheritance-free implementation look like?


Thanks for pointing it out. I think I needed to reword that item.

What I meant is that you don't need a class hierarchy to implement a prototype. You can have a working prototype right in the base class, so no inheritance is really necessary (if you don't have subclasses).

On the other hand, the factory method doesn't really make sense without a class hierarchy.