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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.244.250