- When a client needs to create a set of objects that are alike or differ from each other only in terms of their state and it is expensive to create such objects in terms of the time and the processing involved.
- As an alternative to building numerous factories that mirror the classes to be instantiated (as in the Factory Method).
In such cases, the Prototype pattern suggests to:
- Create one object upfront and designate it as a prototype object.
- Create other objects by simply making a copy of the prototype object and making required modifications.
In the real world, we use the Prototype pattern on many occasions to reduce the time and effort spent on different tasks. The following are two such examples:
- New Software Program Creation: Typically programmers tend to make a copy of an existing program with similar structure and modify it to create new programs.
- Cover Letters: When applying for positions at different organizations, an applicant may not create cover letters for each organization individually from scratch. Instead, the applicant would create one cover letter in the most appealing format, make a copy of it and personalize it for every organization.
As can be seen from the examples above, some of the objects are created from scratch, whereas other objects are created as copies of existing objects and then modified. But the system or the process that uses these objects does not differentiate between them on the basis of how they are actually created. In a similar manner, when using the Prototype pattern, a system should be independent of the creation, composition and representation details of the objects it uses. One of the requirements of the prototype object is that it should provide a way for clients to create a copy of it. By default, all Java objects inherit the builtin clone() method from the topmost java.lang.Object class. The built-in clone() method creates a clone of the original object as a shallow copy. Furthermore, the Prototype specifies the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.