Java Reference
In-Depth Information
Prototype
Pattern Properties
Type: Creational, Object
Level: Single Class
Purpose
To make dynamic creation easier by defining classes whose objects can create duplicates of themselves.
Introduction
In the PIM, you want to be able to copy an address entry so that the user doesn't have to manually enter all the
information when creating a new contact. One way to solve this is to perform the following steps:
Create a new Address object.
Copy the appropriate values from the existing Address .
While this approach solves the problem, it has one serious drawback—it violates the object-oriented principle of
encapsulation. To achieve the solution mentioned above, you have to put method calls to copy the Address
information, outside of the Address class. This means that it becomes harder and harder to maintain the Address
code, since it exists throughout the code for the project. It is also difficult to reuse the Address class in some new
project in the future.
The copy code really belongs in the Address class itself, so why not instead define a “copy” method in the class?
This method produces a duplicate of the Address object with the same data as the original object—the prototype.
Calling the method on an existing Address object solves the problem in a much more maintainable way, much
truer to good object-oriented coding practices.
Applicability
Use the Prototype pattern when you want to create an object that is a copy of an existing object.
Description
The Prototype pattern is well named; as with other prototypes, it has an object that is used as the basis to create a
new instance with the same values. Providing a “create based on existing state ” behavior allows programs to
perform operations like user-driven copy, and to initialize objects to a state that has been established through use
of the system. This is often preferable to initializing the object to some generic set of values.
Classic examples for this pattern exist in graphic and text editors, where copy-paste features can greatly improve
user productivity. Some business systems use this approach as well, producing an initial model from an existing
business object. The copy can then be modified to its desired new state.
Implementation
The Prototype class diagram is shown in Figure 1.4 .
Figure 1.4. Prototype class diagram
To implement Prototype, you need:
 
 
Search WWH ::




Custom Search