Prototype Pattern in java
The prototype pattern is a creational design pattern. Prototype patterns is required, when object creation is time consuming,
and costly operation, so we create object with existing object itself. One of the best available way to create object from existing objects
are clone() method. Clone is the simplest approach to implement prototype pattern. However, it is your call to decide how to copy existing
object based on your business model.
If you are using clone method, then it is upto you to decide whether go for shallow copy or deep copy based on your business
need. Here is the UML structure of the Prototype design pattern:

Here is a simple example to demonstrate the pattern to make you understand. Code is slightly modifed when compared with UML structure.
We added ColorStore class to store existing objects.
Abstract class implementing Clonable interface:
package com.java2novice.prototype;
public abstract class Color implements Cloneable {
protected String colorName;
abstract void fillColor();
public Object clone(){
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return clone;
}
}
|
Concrete class extending above abstract class:
package com.java2novice.prototype;
public class RedColor extends Color{
public RedColor() {
this.colorName = "RED";
}
@Override
void fillColor() {
System.out.println("filling red color...");
}
}
|
Concrete class extending above abstract class:
package com.java2novice.prototype;
public class GreenColor extends Color{
public GreenColor() {
this.colorName = "Green";
}
@Override
void fillColor() {
System.out.println("filling green color...");
}
}
|
Below code creates all objects and maintain object store. All object requests will be cloned from this store:
package com.java2novice.prototype;
import java.util.HashMap;
import java.util.Map;
public class ColorStore {
private static Map<String, Color> colorMap = new HashMap<String, Color>();
static {
colorMap.put("red", new RedColor());
colorMap.put("green", new GreenColor());
}
public static Color getColor(String colorName){
return (Color) colorMap.get(colorName).clone();
}
}
|
Prototype pattern demo class:
package com.java2novice.prototype;
public class PrototypeTest {
public static void main(String a[]){
ColorStore.getColor("red").fillColor();
ColorStore.getColor("green").fillColor();
ColorStore.getColor("green").fillColor();
ColorStore.getColor("red").fillColor();
}
}
|
|