- Mastering Python Design Patterns
- Sakis Kasampalis
- 339字
- 2021-08-06 19:21:43
Use cases
The Prototype pattern is useful when we have an existing object and we want to create an exact copy of it. A copy of an object is usually required when we know that parts of the object will be modified but we want to keep the original object untouched. In such cases, it doesn't make sense to recreate the original object from scratch [j.mp/protpat].
Another case where Prototype comes in handy is when we want to duplicate a complex object. By duplicating a complex object, we can think of an object that is populated from a database and has references to other objects that are also populated from a database. It is a lot of effort to create an object clone by querying the database(s) multiple times again. Using Prototype for such cases is more convenient.
So far, we have covered only the reference versus copy issue, but a copy can be further divided into a deep copy versus a shallow copy. A deep copy is what we have seen so far: all data of the original object are simply copied in the clone, without making any exceptions. A shallow copy relies on references. We can introduce data sharing, and techniques like copy-on-write to improve the performance (such as clone creation time) and the memory usage. Using shallow copies might be worthwhile if the available resources are limited (such as embedded systems) or performance is critical (such as high-performance computing).
In Python, we can do shallow copies using the copy.copy()
function. Quoting the official Python documentation, the differences between a shallow copy (copy.copy()
) and a deep copy (copy.deepcopy()
) in Python are [j.mp/py3copy] as follows:
- "A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
- A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original."
Can you think of any examples where using shallow copies is better than using deep copies?
- 數(shù)據(jù)庫程序員面試筆試真題與解析
- C語言程序設(shè)計(第2 版)
- Java開發(fā)入行真功夫
- YARN Essentials
- C++ 從入門到項目實踐(超值版)
- The HTML and CSS Workshop
- Spring快速入門
- Linux C編程:一站式學習
- Scala for Machine Learning(Second Edition)
- Spring 5 Design Patterns
- Backbone.js Testing
- jQuery Mobile Web Development Essentials(Second Edition)
- JavaWeb從入門到精通(視頻實戰(zhàn)版)
- 一覽眾山小:ASP.NET Web開發(fā)修行實錄
- Learning TypeScript