简体   繁体   English

原型设计模式

[英]Prototype Design Pattern

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 ? 原型设计模式在这里的重要性是什么?

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. 执行该行代码后,您仍然只有一个 Typist对象。 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. 执行完这一行代码后,您现在有了两个 Typist对象,可以彼此独立地使用和操作它们。 Any change made to one variable will not be reflected in the other, because they reference different objects. 对一个变量所做的任何更改都不会反映在另一个变量中,因为它们引用了不同的对象。

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. 您需要决定想要什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM