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

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.

主站蜘蛛池模板: 正镶白旗| 宜都市| 饶平县| 天全县| 衢州市| 蓝田县| 吴旗县| 通州区| 滨海县| 韶关市| 陇西县| 韶山市| 乌恰县| 大洼县| 崇仁县| 正蓝旗| 柳州市| 土默特左旗| 绿春县| 玛沁县| 綦江县| 宣汉县| 扶绥县| 牙克石市| 南汇区| 芜湖市| 四平市| 台湾省| 丰都县| 巩留县| 海原县| 南京市| 米易县| 连城县| 临沂市| 晴隆县| 博客| 于田县| 渝中区| 绥化市| 长沙市|