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

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.

主站蜘蛛池模板: 项城市| 五寨县| 贵德县| 沾化县| 株洲市| 宿州市| 青川县| 开远市| 南开区| 万山特区| 丰县| 平泉县| 阳城县| 外汇| 遂宁市| 壤塘县| 玉屏| 左贡县| 屏山县| 许昌县| 朔州市| 宁波市| 贡嘎县| 城口县| 张家港市| 石首市| 永新县| 上蔡县| 宁河县| 芦溪县| 沙雅县| 息烽县| 固镇县| 郑州市| 思茅市| 措美县| 雅江县| 陇南市| 石狮市| 吐鲁番市| 怀远县|