Reputation: 45
Why I need to use Prototype Design Pattern ? Instead of that I can directly assign that value right ? for example
as per Prototype Design Pattern we have to clone like :
Typist typistCopy = (Typist)typist.Clone();
same I can do as:
Typist typistCopy = typist;
What's importance of Prototype Design Pattern here ?
Upvotes: 0
Views: 239
Reputation: 77304
To add a real world analogy:
Page paper = (Page)yourPaper.Clone();
This creates a copy. Now there's two pages of paper, you have your original and somebody was handed the copy.
Page paper = yourPaper;
No copy was made. You have a page of paper and somebody else grabbed it, too. Now you both hold onto that single page of paper.
You need to decide what you want.
Upvotes: 0
Reputation: 218877
The two operations you demonstrate do different things. Which one you need depends on what you want to do.
This does not create a copy/clone of the object:
Typist typistCopy = typist;
All it does it create a new variable which references the same object in memory. After executing that line of code, you still have only one Typist
object. You just have two variables referencing it. Any changes made to one variable will be reflected in both, because they both reference the same object.
On the other hand, this creates a copy or clone of the object:
Typist typistCopy = (Typist)typist.Clone();
(Or, at least, allows the object itself to decide if a copy/clone is necessary and performs its own encapsulated logic as to what that means for the object.)
After executing that line of code, you now have two Typist
objects which can be used and manipulated independently of one another. Any change made to one variable will not be reflected in the other, because they reference different objects.
Upvotes: 3