What's the point of the Prototype design pattern?

user1905391 picture user1905391 · Dec 15, 2012 · Viewed 25k times · Source

So I'm learning about design patterns in school. Today I was told about the 'Prototype' design pattern.

I must be missing something, because I don't see the benefits from it. I've seen people online say it's faster than using new but this doesn't make sense; at some point, regardless of how the new object is created, memory needs to be allocated for it.

Doesn't this pattern run in the same circles as the 'chicken or egg' problem? Since the Prototype pattern essentially is just cloning objects, at some point the original object must be created itself (i.e. not cloned). This would mean that I need to have an existing copy of every object I want to clone already ready to clone?

Can anyone explain what the use of this pattern is?

Answer

marcus erronius picture marcus erronius · Dec 15, 2012

The prototype pattern has some benefits, for example:

  • It eliminates the (potentially expensive) overhead of initializing an object
  • It simplifies and can optimize the use case where multiple objects of the same type will have mostly the same data

For example, say your program uses objects that are created from data parsed from mostley unchanging information retrieved over the network. Rather than retrieving the data and re-parsing it each time a new object is created, the prototype pattern can be used to simply duplicate the original object whenever a new one is needed.

Also, say that object may have data that uses up large amounts of memory, such as data representing images. Memory can be reduced by using a copy-on-write style inheritance, where the original, unduplicated data is shown until the code attempts to change that data. Then, the new data will mask to reference to the original data.