- Design Patterns and Best Practices in Java
- Kamalmeet Singh Adrian Ianculescu LUCIAN PAUL TORJE
- 219字
- 2021-06-25 20:52:35
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.
- Python數(shù)據(jù)分析入門(mén)與實(shí)戰(zhàn)
- ASP.NET MVC4框架揭秘
- Building a Game with Unity and Blender
- Python數(shù)據(jù)可視化之Matplotlib與Pyecharts實(shí)戰(zhàn)
- FLL+WRO樂(lè)高機(jī)器人競(jìng)賽教程:機(jī)械、巡線與PID
- 用案例學(xué)Java Web整合開(kāi)發(fā)
- 區(qū)塊鏈項(xiàng)目開(kāi)發(fā)指南
- BeagleBone Robotic Projects(Second Edition)
- 石墨烯改性塑料
- Machine Learning for OpenCV
- CryENGINE Game Programming with C++,C#,and Lua
- 讀故事學(xué)編程:Python王國(guó)歷險(xiǎn)記
- Visual FoxPro程序設(shè)計(jì)實(shí)驗(yàn)教程
- Learning Puppet
- R語(yǔ)言與網(wǎng)站分析