官术网_书友最值得收藏!

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?

主站蜘蛛池模板: 辽阳市| 霍林郭勒市| 平罗县| 恩施市| 上思县| 潞西市| 阿瓦提县| 大兴区| 沙雅县| 余庆县| 博罗县| 安阳县| 蛟河市| 紫阳县| 高州市| 镇江市| 辛集市| 舒城县| 五大连池市| 兴海县| 荆州市| 山西省| 东兰县| 互助| 偃师市| 宁河县| 石城县| 神池县| 潢川县| 余江县| 湄潭县| 恭城| 翁源县| 贞丰县| 盘山县| 当阳市| 台南市| 建宁县| 花莲县| 利津县| 阿克苏市|