Design Pattern Download: The Prototype Pattern
The Prototype pattern is a Creational Pattern used in software engineering when you want to create a new object but creating that object would be too expensive or take too much processing, so you use an already created object as the prototype and create a clone.
Example
Consider this, you are an evil Sith Emperor set on conquering the galaxy. Your last army of robot minions was not capable of helping you towards this goal, however you had one henchman who was so capable, so effective and so not a robot! It made you think “If only I had an army of him, conquering the galaxy would be a no-brainer.”
but raising 10,000 Jango Fett’s from children is no easy task! it takes a lot of time and resources to re-create this specimen over and over again. Sadly, your dreams are dashed… or are they?
The answer? Cloning!!!
When to use the Prototype?
- When creating an object requires a lot of resources but you need multiple of them.
- When you wan’t multiple identical objects to use.
What is the Prototype Pattern composed of?
- The Prototype interface (an interface which declares one method getClone() which will return a Prototype)
- The Prototype ( a class which implements the Prototype interface allowing us to make clones of an instance of it)
Implementation
The Prototype 📐
The prototype simply states that any implementing class must be clone-able.
The Human 🧍
The Human has some instance variables, one of which SSN is very difficult and time consuming to create, if we wanted to create and army of Humans using the first constructor it would take a lot of time and resources.
Luckily we do not care about our soldiers :D and it doesn’t matter if they all have to share social security payments in the future so we are ok 👍 having them share an SSN.
We can create one Human using the first constructor (The Original) and then create our army using the getClone() method (which uses the second constructor) in order to get the rest of our Humans (the clones).
It would look a little like this…