Java Reference
In-Depth Information
Prototype - Provides a copy method. That method returns an instance of the same class with the same values as
the original Prototype instance. The new instance can be a deep or shallow copy of the original (see the Benefits
and Drawbacks section of this pattern).
Benefits and Drawbacks
The Prototype is helpful because it allows systems to produce a copy of a usable object, with variables already set
to a (presumably) meaningful value, rather than depending on some base state defined in the constructor. An
example of Prototype use is shown in Figure 1.5 .
Figure 1.5. Example of Prototype use
A key consideration for this pattern is copy depth.
A shallow copy duplicates only the top-level elements of a class; this provides a faster copy, but isn't suitable for
all needs. Since references are copied from the original to the copy, they still refer to the same objects. The
lower-level objects are shared among copies of the object, so changing one of these objects affects all of the
copies.
Deep copy operations replicate not only the top-level attributes, but also the lower-level objects. This typically
takes longer than shallow copy operations, and can be very costly for objects with an arbitrarily complex structure.
This makes sure that changes in one copy are isolated from other copies.
By its nature, the clone method in Object supports only one form of copy. For cases where you must support
multiple methods of post-creation initialization.
Pattern Variants
Pattern variants include the following:
Copy constructor - One variant of the prototype is a copy constructor. A copy constructor takes an instance of
the same class as an argument and returns a new copy with the same values as the argument.
Example 1.17 Copy constructor
public class Prototype {
private int someData;
// some more data
public Prototype(Prototype original) {
super();
this.someData = original.someData;
//copy the rest of the data
}
// rest of code
}
An example is the String class, where you can create a new String instance by calling for instance: new
String(“text”);
 
 
Search WWH ::




Custom Search