473,765 Members | 1,967 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Confusion in prototype pattern

sumittyagi
202 Recognized Expert New Member
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.

Expand|Select|Wrap|Line Numbers
  1. /** Prototype Class **/
  2. public class Cookie implements Cloneable {
  3.  
  4.    public Object clone()
  5.    {
  6.        try{
  7.           //In an actual implementation of this pattern you would now attach references to
  8.            //the expensive to produce parts from the copies that are held inside the prototype.
  9.             return this.getClass().newInstance();  // confused here.
  10.       }
  11.        catch(InstantiationException e)
  12.        {
  13.           e.printStackTrace();
  14.           return null;
  15.        }
  16.    }
  17. }
  18.  
  19. /** Concrete Prototypes to clone **/
  20. public class CoconutCookie extends Cookie { }
  21.  
  22. /** Client Class**/
  23. public class CookieMachine
  24. {
  25.  
  26.   private Cookie cookie;//could have been a private Cloneable cookie; 
  27.  
  28.     public CookieMachine(Cookie cookie) { 
  29.         this.cookie = cookie; 
  30.     } 
  31.     public Cookie makeCookie() { 
  32.       return (Cookie)cookie.clone(); 
  33.     } 
  34.     public Object clone() { } 
  35.  
  36.     public static void main(String args[]){ 
  37.         Cookie tempCookie =  null; 
  38.         Cookie prot = new CoconutCookie(); 
  39.         CookieMachine cm = new CookieMachine(prot); 
  40.         for(int i=0; i<100; i++) 
  41.             tempCookie = cm.makeCookie(); 
  42.     } 
  43. }
  44.  


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.

(Prototype Pattern link on wikipedia)

Thanks in Advance for any guidance.
Jun 6 '07 #1
12 3029
JosAH
11,448 Recognized Expert MVP
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.

(Prototype Pattern link on wikipedia)

Thanks in Advance for any guidance.
The 'this' object can be either a Cookie or any derived object thereof (such as a
CoconutCookie). The corresponding class is found using the 'getClass()' method
which can create a new object of that class. Using one of the Cookie types as
a prototype (or 'exemplar' in SmallTalk) it can create new instances of itself which
is functionally equivalent to the clone() functionality. Maybe your confusion wouldn't
have existed if the wiki example had named the method 'duplicate()' instead of
'clone()'?

kind regards,

Jos
Jun 6 '07 #2
sumittyagi
202 Recognized Expert New Member
The 'this' object can be either a Cookie or any derived object thereof (such as a
CoconutCookie). The corresponding class is found using the 'getClass()' method
which can create a new object of that class. Using one of the Cookie types as
a prototype (or 'exemplar' in SmallTalk) it can create new instances of itself which
is functionally equivalent to the clone() functionality. Maybe your confusion wouldn't
have existed if the wiki example had named the method 'duplicate()' instead of
'clone()'?

kind regards,

Jos
Thanks jos for your reply.
But What I got from the explaination of prototype pattern is not getting reflected in the code.

We use prototype pattern when the object creation and initialization is quite expensive. I mean when we want to get the exact copy(including its current state) of the existing complex object.

And what they did is, created a new object instead of copying it(existing state of object is not retained in this case).

And its not the name of the method that have confused me, but they have actually overridden the clone method of Object class.

Please guide me in this context.
Thanks again!
Jun 6 '07 #3
sumittyagi
202 Recognized Expert New Member
Thanks jos for your reply.
But What I got from the explaination of prototype pattern is not getting reflected in the code.

We use prototype pattern when the object creation and initialization is quite expensive. I mean when we want to get the exact copy(including its current state) of the existing complex object.

And what they did is, created a new object instead of copying it(existing state of object is not retained in this case).

And its not the name of the method that have confused me, but they have actually overridden the clone method of Object class.

Please guide me in this context.
Thanks again!

Ok fine!!!
I think my answer lies here
Expand|Select|Wrap|Line Numbers
  1.            //In an actual implementation of this pattern you would now attach references to
  2.            //the expensive to produce parts from the copies that are held inside the prototype.
  3.  
Means they are cloning the internal complex parts of the complex object, rather than cloning the whole complex object.

Thanks for your support Jos.
Please correct me if I have misunderstood anything.
Jun 6 '07 #4
JosAH
11,448 Recognized Expert MVP
Your question stayed in the back of my head for the entire day. Until I realized
something because of this sentense of yours:

We use prototype pattern when the object creation and initialization is quite expensive.
You're mixing up two different patterns:

1) the Prototype pattern or 'exemplar' where you basically have one (unknown)
object already and you want to tell something "give me another one of those".

2) the Proxy pattern where an object is quite expensive to create. A proxy can
handle the el-cheapo questions and acts as if it were the expensive object. Once
you ask a question that actually needs the expensive object itself, the Proxy
will create it for you.

Check them both out: the Proxy pattern and the Prototype pattern.

kind regards,

Jos
Jun 6 '07 #5
sumittyagi
202 Recognized Expert New Member
Your question stayed in the back of my head for the entire day. Until I realized
something because of this sentense of yours:



You're mixing up two different patterns:

1) the Prototype pattern or 'exemplar' where you basically have one (unknown)
object already and you want to tell something "give me another one of those".

2) the Proxy pattern where an object is quite expensive to create. A proxy can
handle the el-cheapo questions and acts as if it were the expensive object. Once
you ask a question that actually needs the expensive object itself, the Proxy
will create it for you.

Check them both out: the Proxy pattern and the Prototype pattern.

kind regards,

Jos
Actually I am learning design patterns now a days. I have just read about creational patterns. I will now read structural patterns. I will come back to this thread when I am done with proxy pattern, to get your guidance again.

Thanks a lot for all your help.
Jun 7 '07 #6
sumittyagi
202 Recognized Expert New Member
Your question stayed in the back of my head for the entire day. Until I realized
something because of this sentense of yours:



You're mixing up two different patterns:

1) the Prototype pattern or 'exemplar' where you basically have one (unknown)
object already and you want to tell something "give me another one of those".

2) the Proxy pattern where an object is quite expensive to create. A proxy can
handle the el-cheapo questions and acts as if it were the expensive object. Once
you ask a question that actually needs the expensive object itself, the Proxy
will create it for you.

Check them both out: the Proxy pattern and the Prototype pattern.

kind regards,

Jos
Hi! jos!
I don't think I am mixing the two patterns.
What I got from wikipeida explainations is:
1. Prototype pattern is a creational pattern, and hence deals with the creation of objects.
Now the purpose of prototype pattern is:
* there may be some standard states of any object (and reaching upto that state could be quite expensive).
* after reaching that state, we could need to change the state for our purpose to be accomplished in a particular scenario.
* there might be more than one scenario which needs to change the state from the standard state.

* so we make a copy of the standard state, and then customize the new object according to our requirements.
* in this way our particular requirement is also fulfilled, and standard state is also not changed, so that we can utilize in another scenario.
(all this explaination is my own assumption, its not written in article, so it may be wrong, so please correct me if I am wrong anywhere)


2. Now comming to proxy pattern:
proxy pattern is a structural pattern, and it deals with the overall structure of the application, rather than simply creation of objects.

Now here I paste some paras from the explaination about proxy pattern from article.
A proxy, in its most general form, is a class functioning as an interface to another thing. The other thing could be anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate.....

....Typically one instance of the complex object is created, and multiple proxy objects are created, all of which contain a reference to the single original complex object. Any operations performed on the proxies are forwarded to the original object. Once all instances of the proxy are out of scope, the complex object's memory may be deallocated.... .

* So here the complex object is basically a utility object, other parts of the application simply utilize it, but they don't change it state.

This is not at all to contradict you, but its just brainstorming session, which will clear doubts of both of us.
So please correct me if I am wrong any where.

I can't even think of contradicting you as I am a great fan of your articles, they are marvellous.
Jun 7 '07 #7
r035198x
13,262 MVP
Expand|Select|Wrap|Line Numbers
  1. /** Prototype Class **/
  2. public class Cookie implements Cloneable {
  3.  
  4. public Object clone()
  5. {
  6. try{
  7. //In an actual implementation of this pattern you would now attach references to
  8. //the expensive to produce parts from the copies that are held inside the prototype.
  9. return this.getClass().newInstance(); // confused here.
  10. }
  11. catch(InstantiationException e)
  12. {
  13. e.printStackTrace();
  14. return null;
  15. }
  16. }
  17. }
  18.  
  19. ....}
  20.  


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.

(Prototype Pattern link on wikipedia)

Thanks in Advance for any guidance.
You didn't read the comment! They just returned the new instance to make it compile but the comment says instead of returning a new instance, you would now "attach references to
the expensive to produce parts from the copies that are held inside the prototype." before returning it.
Jun 7 '07 #8
sumittyagi
202 Recognized Expert New Member
You didn't read the comment! They just returned the new instance to make it compile but the comment says instead of returning a new instance, you would now "attach references to
the expensive to produce parts from the copies that are held inside the prototype." before returning it.
Thanks r035198 for ur reply, I noticed that and indicated that above.
I and jos were discussing the differences between prototype and proxy pattern.
Jun 7 '07 #9
JosAH
11,448 Recognized Expert MVP
Hi! jos!
I don't think I am mixing the two patterns.
What I got from wikipeida explainations is:
1. Prototype pattern is a creational pattern, and hence deals with the creation of objects.
Now the purpose of prototype pattern is:
* there may be some standard states of any object (and reaching upto that state could be quite expensive).
* after reaching that state, we could need to change the state for our purpose to be accomplished in a particular scenario.
* there might be more than one scenario which needs to change the state from the standard state.

* so we make a copy of the standard state, and then customize the new object according to our requirements.
* in this way our particular requirement is also fulfilled, and standard state is also not changed, so that we can utilize in another scenario.
(all this explaination is my own assumption, its not written in article, so it may be wrong, so please correct me if I am wrong anywhere)


2. Now comming to proxy pattern:
proxy pattern is a structural pattern, and it deals with the overall structure of the application, rather than simply creation of objects.

Now here I paste some paras from the explaination about proxy pattern from article.
A proxy, in its most general form, is a class functioning as an interface to another thing. The other thing could be anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate.....

....Typically one instance of the complex object is created, and multiple proxy objects are created, all of which contain a reference to the single original complex object. Any operations performed on the proxies are forwarded to the original object. Once all instances of the proxy are out of scope, the complex object's memory may be deallocated.... .

* So here the complex object is basically a utility object, other parts of the application simply utilize it, but they don't change it state.

This is not at all to contradict you, but its just brainstorming session, which will clear doubts of both of us.
So please correct me if I am wrong any where.

I can't even think of contradicting you as I am a great fan of your articles, they are marvellous.
I opened the Holy Scriptures (the Gang of Four book) and proxies are used when
the real thing can be expensive to create. Prototypes have nothing to do with
a 'real thing being expensive' or not. Prototypes implement an interface (like
Cloneable) that allows a caller to say "give me another one of you".

The Holy Scriptures are correct of course ;-)

kind regards,

Jos
Jun 7 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

1
3162
by: Doug Farrell | last post by:
Hi all, I'm trying to do the following from within a code module: import re # text to match text = "Good morning x something /x, how are you today x something else /x"
5
1531
by: tomlong | last post by:
What is the reason why Javascript, unlike other languages, uses prototype instead of classical inheritance? I know you can do classical inheritance with a bit of work, but it seems like the kind of thing that would be nice out of the box, and I don't understand why prototype is preferable. Tom Longson (nym) http://igargoyle.com/
0
1203
by: FluffyCat | last post by:
Last week I continued my series of design patterns examples using PHP 5 with the Observer Pattern. Here now is my 15th example, the Prototype pattern. http://www.fluffycat.com/PHP-Design-Patterns-Prototype/ In the Prototype Pattern, we create new objects by cloning a standard one we already have. Pretty simple and fairly useful.
3
3653
by: Beta What | last post by:
Hello, I have a question about casting a function pointer. Say I want to make a generic module (say some ADT implementation) that requires a function pointer from the 'actual/other modules' that takes arguments of type (void *) because the ADT must be able to deal with any type of data. In my actual code, I will code the function to take arguments of their real types, then when I pass this pointer through an interface function, I...
2
1306
by: VJ | last post by:
I tried to write sample code to get understanding of javascript's prototypal inheritance (along with the variety of function calling choices.. ) During the process, I got myself throughly confused. Can anyone explain following behavior here is my code: <html>
1
4291
by: v4vijayakumar | last post by:
Can "c++ conversion operator" be considered as an example for Prototype design pattern? Following example explains, C++ conversion operator. #include <iostream> #include <string> using namespace std; class test
83
4231
by: liketofindoutwhy | last post by:
I am learning more and more Prototype and Script.aculo.us and got the Bungee book... and wonder if I should get some books on jQuery (jQuery in Action, and Learning jQuery) and start learning about it too? Once I saw a website comparing Prototype to Java and jQuery to Ruby... but now that I read more and more about Prototype, it is said that Prototype actually came from Ruby on Rails development and the creator of Prototype created it...
1
5412
by: p.tilhoo | last post by:
Hello there, I am a programmer mostly using c# and just started using Javascript. I am trying to use prototype to declare and use an object and having difficulties in coding for nested objects. Basically my object called layercontrol will contain and array of layergroup which in turn contains map layer objects. The layergroup and layer object should be just like any object of properties and
4
5015
by: Pallav singh | last post by:
Hi , when should i select Factory Method / Prototype Design Pattern during my design phase ?? as both look similar to me Thanks in Advance Thanks Pallav
0
9568
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9398
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9951
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9832
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5421
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3924
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3531
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2805
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.