Confusion in prototype pattern
Hi everybody!
I am having a difficulty in understanding the prototype pattern. Actually I got the idea behind it, but the example given in wikipedia for this pattern have confused me.
The code is as follows.
/** Prototype Class **/
publicclass Cookieimplements Cloneable{
public Object clone()
{
try{
//In an actual implementation of this pattern you would now attach references to
//the expensive to produce parts from the copies that are held inside the prototype.
return this.getClass().newInstance();// confused here.
}
catch(InstantiationException e)
{
e.printStackTrace();
returnnull;
}
}
}
/** Concrete Prototypes to clone **/
publicclass CoconutCookieextends Cookie{}
/** Client Class**/
publicclass CookieMachine
{
private Cookie cookie;//could have been a private Cloneable cookie;
public CookieMachine(Cookie cookie){
this.cookie = cookie;
}
public Cookie makeCookie(){
return (Cookie)cookie.clone();
}
public Object clone(){}
publicstaticvoid main(String args[]){
Cookie tempCookie =null;
Cookie prot =new CoconutCookie();
CookieMachine cm =new CookieMachine(prot);
for(int i=0; i<100; i++)
tempCookie = cm.makeCookie();
}
}
Now my confusion lies here.
>> return this.getClass().newInstance()
in the clone method.
On one hand it is said, we create clone of the object, but in reality new instance is created. I am not able to understand the logic.
Please help me out.
Thanks in Advance for any guidance.

