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

Starting from a prototype

The whole idea of a prototype is to be able to clone an object easily. There are a number of reasons you may want to do this:

  • Creating your object is very expensive. You need to fetch it from the database.
  • You create objects that are similar but different from one another, and you don't want to repeat similar parts over and over again.

There are also more advanced reasons to use this pattern. JavaScript language, for example, uses prototypes to implement inheritance-like behavior without having classes.

Luckily, Kotlin fixes the broken Java clone() method. For data classes, there's the copy() method, which takes an existing data class, and creates a new copy of it, optionally changing some of its attributes in the process:

val pcFromWarehouse = PC() // Our boring PC

val pwnerPC = pcFromWarehouse.copy(graphicCard = "nKCF 8999ZTXX",
ram = "16GB BBR6") // Amazing PC

println(pwnerPC) // Make sure that PC created correctly

By default, the clone() method creates a shallow copy, which may be unexpected for less experienced developers. It's very hard to implement the clone() method correctly in Java. You can read about the various pitfalls at https://dzone.com/articles/shallow-and-deep-java-cloning.

Similar to what we've seen in the Builder design pattern, named arguments allow us to specify attributes that we can change in any order. 

The only thing that's left is for you to count the cash and buy some more of those nKCF graphic cards. Just in case.

主站蜘蛛池模板: 岑溪市| 通州区| 平度市| 义马市| 浦江县| 松桃| 德格县| 白银市| 庆云县| 尚志市| 奉节县| 鲁甸县| 柳林县| 英德市| 阳山县| 涪陵区| 洛扎县| 措勤县| 京山县| 昭平县| 红原县| 莫力| 曲沃县| 无为县| 常德市| 垫江县| 买车| 阜平县| 右玉县| 澳门| 浦江县| 东丰县| 朝阳市| 夹江县| 通化市| 天全县| 慈溪市| 宁陵县| 阳高县| 泸西县| 伊春市|