While addressing the same problem as the Factory Method and Abstract Factory patterns, the Prototype pattern offers a different, more flexible way of achieveing the same result.
Other uses of the Prototype pattern include:
- 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.
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.
SHALLOW COPY VERSUS DEEP COPY
When an object is cloned as a shallow copy:
- The original top-level object and all of its primitive members are duplicated.
- Any lower-level objects that the top-level object contains are not duplicated. Only references to these objects are copied. This results in both the orginal and the cloned object referring to the same copy of the lower-level object.
class Person implements Cloneable {
//Lower-level object
private Car car;
private String name;
public Car getCar() {
return car;
}
public String getName() {
return name;
}
public void setName(String s) {
name = s;
}
public Person(String s, String t) {
name = s;
car = new Car(t);
}
public Object clone() {
//shallow copy
try {
return super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}
}
|
In contrast, when an object is cloned as a deep copy:
- The original top-level object and all of its primitive members are duplicated.
- Any lower-level objects that the top-level object contains are also duplicated. In this case, both the orginal and the cloned object refer to two different lower-level objects.
class Person implements Cloneable {
//Lower-level object
private Car car;
private String name;
public Car getCar() {
return car;
}
public String getName() {
return name;
}
public void setName(String s) {
name = s;
}
public Person(String s, String t) {
name = s;
car = new Car(t);
}
public Object clone() {
//Deep copy
Person p = new Person(name, car.getName());
return p;
}
}
|
No comments:
Post a Comment