Sunday, August 17, 2014

Prototype Pattern

At time prototype looks to heavy a word to me for this pattern. A simple and more intuitive name is Clone or Copy pattern. But clone and copy names take a lot of sheen out of the things. :-). Anyway, coming back to prototype pattern, it's just a smart cloning mechanism. The cloning logic is encapsulated neatly inside a method. Whenever you need the clone of a object, call clone method on that object. The decision which is important for Prototype pattern is how deep or shallow you want it to be.

The cloning interface for better management

public interface Cloneable {
public Object clone();
}

Class which has cloning capability

public class Actor implements Cloneable {

private final String name;
private final List<String> movieList;

public Actor(String name, List<String> movieList) {
this.name = name;
this.movieList = movieList;
}

@Override
public Object clone() {
      //In future when the cloning technology will be prevalent, this might be a contentious
 //issue that how the wealth will be shared between originals and clones. A sure conflict
 //of interest exists here. From the pattern perspective, we can have a shallow copy which is
 //done here or we can have a deep copy
Actor clone = new Actor(name, movieList);
return clone;
}

public String getName() {
return name;
}

public List<String> getMovieList() {
return movieList;
}
}

Main class

public class PrototypeMain {

public static void main(String[] args) {
// Let make Arnie
List<String> movieList = new ArrayList<String>();
movieList.add("Commondo");
movieList.add("True Lies");
// We can add more but let's stop here. Let's do pattern and not movies
// :)

Actor arnie = new Actor("Arnold", movieList);
// Sounds like "The 6th day"
Actor clone = (Actor) arnie.clone();

if (clone.getMovieList() == arnie.getMovieList()) {
System.out.println("Hmmm serious issue of ownership");
}
}
}

This pattern is quite useful in one situation, when one has to copy a set of records in database which are connected through a parent child relationship. but while copying we do not want their original primary keys, but the newly generated keys. With proper cascading set at top object, (I am assuming ORM being used here) and clone at all levels, whole tree can be cloned. With persist called on the top object, the tree is created in the database.

Articles on Software Design and Patterns

No comments:

Post a Comment