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

Back to our bases

HQ is a special building that can produce other buildings. It keeps track of all the buildings it had built up until now. The same type of building can be built more than once:

class HQ {
val buildings = mutableListOf<Building<*, Unit>>()

fun buildBarracks(): Barracks {
val b = Barracks()
buildings.add(b)
return b
}

fun buildVehicleFactory(): VehicleFactory {
val vf = VehicleFactory()
buildings.add(vf)
return vf
}
}

You may be wondering what the star (*) means as regards generics. It's called a star projection, and it means I don't know anything about this type. It's similar to Java's raw types, but it's type safe.

All other buildings produce units. Units can be either infantry or armored vehicle:

interface Unit 

interface Vehicle : Unit

interface Infantry : Unit

Infantry can be either riflemen or rocket soldier:

class Rifleman : Infantry

class RocketSoldier : Infantry

enum class InfantryUnits {
RIFLEMEN,
ROCKET_SOLDIER
}

Here we see the enum keyword for the first time. Vehicles are either tanks or armored personnel carriers (APCs):

class APC : Vehicle

class Tank : Vehicle

enum class VehicleUnits {
APC,
TANK
}

A barracks is a building that produces infantry:

class Barracks : Building<InfantryUnits, Infantry> {
override fun build(type: InfantryUnits): Infantry {
return when (type) {
RIFLEMEN -> Rifleman()
ROCKET_SOLDIER -> RocketSoldier()
}
}
}

We don't need the else block in our when. That's because we use enum, and Kotlin makes sure that when on enum is exhaustive.

A vehicle factory is a building that produces different types of armored vehicles:

class VehicleFactory : Building<VehicleUnits, Vehicle> {
override fun build(type: VehicleUnits) = when (type) {
APC -> APC()
TANK -> Tank()
}
}

We can make sure that we can build different units now:

val hq = HQ()
val barracks1 = hq.buildBarracks()
val barracks2 = hq.buildBarracks()
val vehicleFactory1 = hq.buildVehicleFactory()

And now on to producing units:

val units = listOf(
barracks1.build(InfantryUnits.RIFLEMEN),
barracks2.build(InfantryUnits.ROCKET_SOLDIER),
barracks2.build(InfantryUnits.ROCKET_SOLDIER),
vehicleFactory1.build(VehicleUnits.TANK),
vehicleFactory1.build(VehicleUnits.APC),
vehicleFactory1.build(VehicleUnits.APC)
)

We've already seen the listOf() function from the standard library. It will create a read-only list of different units that our buildings produce. You can iterate over this list and make sure that those are indeed the units we require.

主站蜘蛛池模板: 莫力| 海淀区| 安乡县| 金溪县| 碌曲县| 桃江县| 武山县| 逊克县| 蓬莱市| 鹰潭市| 瑞金市| 安远县| 平和县| 东港市| 陈巴尔虎旗| 宁夏| 光泽县| 仁怀市| 府谷县| 白朗县| 烟台市| 特克斯县| 武宁县| 邳州市| 瑞安市| 科技| 宜川县| 嘉峪关市| 大田县| 若羌县| 石门县| 石狮市| 桓仁| 尚志市| 兴义市| 西丰县| 望城县| 出国| 浦东新区| 纳雍县| 比如县|