- Hands-On Design Patterns with Kotlin
- Alexey Soshin
- 250字
- 2021-06-25 20:49:31
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.
- 數據庫系統原理及MySQL應用教程(第2版)
- Vue.js 3.x快速入門
- Facebook Application Development with Graph API Cookbook
- 基于粒計算模型的圖像處理
- Cross-platform Desktop Application Development:Electron,Node,NW.js,and React
- C語言程序設計教程(第2版)
- SQL for Data Analytics
- Getting Started with PowerShell
- Swift 3 New Features
- 差分進化算法及其高維多目標優化應用
- RabbitMQ Essentials
- Visual C++開發入行真功夫
- Android Wear Projects
- Scratch3.0趣味編程動手玩:比賽訓練營
- Internet of Things with ESP8266