June 2018
Intermediate to advanced
310 pages
6h 32m
English
One may claim that having the VehicleFactory and Barracks classes is too cumbersome. They don't have any state, after all. Instead, we can replace them with objects.
Instead of the previous implementation of buildBarracks(), we can have the following:
fun buildBarracks(): Building<InfantryUnits, Infantry> { val b = object : Building<InfantryUnits, Infantry> { override fun build(type: InfantryUnits): Infantry { return when (type) { InfantryUnits.RIFLEMEN -> Rifleman() InfantryUnits.ROCKET_SOLDIER -> RocketSoldier() } } } buildings.add(b) return b}
We've already seen two different usages of the object keyword: once in the Singleton design pattern, and another time in the Factory Method design pattern. Here is the third way ...
Read now
Unlock full access