Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Please follow the steps to write a small project This is the code that was done before: Step 1 : Transform General class into an

Please follow the steps to write a small project
This is the code that was done before:
Step1: Transform General class into an abstract class
abstract class General(val name: String){
val maxHP: Int =4
var currentHP: Int =0
init {
println("General $name created.")
}
}
Step 2: Implement Simple Factory Pattern
object GeneralFactory {
fun createGeneral(name: String): General {
return when (name){
"LiuBei" -> LiuBei(name)
"CaoCao" -> CaoCao(name)
"SunQuan" -> SunQuan(name)
else -> throw IllegalArgumentException("Unknown general name")
}.apply {
currentHP = maxHP
println("$name has $maxHP health point.")
}
}
}
Step 3: Implement Factory Method Pattern
abstract class GeneralFactory {
abstract fun createRandomGeneral(): General
}
class LordFactory : GeneralFactory(){
private val generatedGenerals = mutableSetOf()
override fun createRandomGeneral(): General {
val possibleGenerals = listOf("LiuBei", "CaoCao", "SunQuan")
val availableGenerals = possibleGenerals.filter { it !in generatedGenerals }
val randomGeneralName = availableGenerals.random()
generatedGenerals.add(randomGeneralName)
return GeneralFactory.createGeneral(randomGeneralName)
}
}
// NonLordFactory can be similarly implemented if needed
Final Step: Modify main function to use factories and add generals to the manager
fun main(){
val manager = GeneralManager
val liuBei = GeneralFactory.createGeneral("LiuBei")
val caoCao = GeneralFactory.createGeneral("CaoCao")
val sunQuan = GeneralFactory.createGeneral("SunQuan")
manager.addGeneral(liuBei)
manager.addGeneral(caoCao)
manager.addGeneral(sunQuan)
val lordFactory = LordFactory()
for (i in 1..3){
val newLord = lordFactory.createRandomGeneral()
manager.addGeneral(newLord)
}
val nonLordFactory = NonLordFactory()
for (i in 1..3){
val newNonLord = nonLordFactory.createRandomGeneral()
manager.addGeneral(newNonLord)
}
val totalGenerals = manager.getGeneralCount()
println("Total number of generals: $totalGenerals")
}
image text in transcribed

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

More Books

Students also viewed these Databases questions