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

Shallow clone versus deep clone

When cloning objects, we should be aware of the deepness of cloning. When we clone an object that contains simple datatypes, such as int and float, or immutable objects, such as strings, we should simply copy those fields to the new object, and that's it.

A problem arises when our objects contain references to other objects. For example, if we have to implement a clone method for a Car class that has an engine and a list of four wheels, we should create not only a new Car object but also a new Engine and four new Wheel objects. After all, two cars cannot share the same engine and the same wheels. This is called a deep clone.

Shallow cloning is a method of cloning only the object that is the subject of cloning. For example, if we have to implement a clone method for a Student object, we are not going to clone the Course object it points to. More than one Student object can point to the same Course object.

In practice, we should decide whether we need deep, shallow, or mixed cloning based on each scenario. Usually, shallow cloning corresponds to the aggregation relation described in Chapter 1, From Object-Oriented to Functional Programming, and deep cloning to the composition relation.

主站蜘蛛池模板: 米易县| 巨野县| 绵阳市| 武强县| 长白| 楚雄市| 油尖旺区| 长沙县| 南昌县| 信阳市| 桂林市| 新密市| 陵水| 冕宁县| 彭阳县| 裕民县| 上虞市| 奇台县| 尼玛县| 蒲江县| 红安县| 宁南县| 民乐县| 黄山市| 天门市| 隆回县| 颍上县| 龙山县| 昭苏县| 巩留县| 西昌市| 灌阳县| 泰和县| 伊宁县| 广元市| 漯河市| 衡阳县| 衡南县| 海盐县| 滦南县| 岐山县|