Saturday, October 23, 2010

Prototype

Prototype object when its creation gets expensive.
Actual object,
public class ExpensiveType implements Cloneable {

    public int i=0;
    public ExpensiveType(){
        System.out.println("Expensive Object creation");
        i=new Random(10).nextInt();
    }
    public int getI(){
        return i;
    }
    public void setI(int i){
        this.i=i;
    }
    public ExpensiveType clone() throws CloneNotSupportedException{
        ExpensiveType clone=(ExpensiveType)super.clone();
        return clone;
    }
} 
A factory to hold reference to once created expensive object,
public class PrototypeFactory {

    private PrototypeFactory(){}
    private static PrototypeFactory s_instance=new PrototypeFactory();
    public static PrototypeFactory getInstance(){
        return s_instance;
    }
    private ExpensiveType actualObject=null;
    public  ExpensiveType prototypeExpensiveObject() throws CloneNotSupportedException{
        if(actualObject==null)
            actualObject=new ExpensiveType();
        return (ExpensiveType) actualObject.clone(); 
    }
} 
client,
public class ActualObjectClient {

    public static void main(String...strings ){
        try {
            ExpensiveType object=PrototypeFactory.getInstance().prototypeExpensiveObject();
            System.out.println(object.getI());
            object.setI(99);
            System.out.println(object.getI());
            object=PrototypeFactory.getInstance().prototypeExpensiveObject();
            System.out.println(object.getI());
        } catch (CloneNotSupportedException e) {
        }
    }
} 
sample output,
Expensive Object creation
-1157793070
99
-1157793070

No comments:

Post a Comment