一、简陋版洗衣机
Test.kt
/*** 程序员B写的代码* 洗衣服*/
fun main(args:Array<String>){var washMachine = WashMachine("小天鹅",size = 12)washMachine.openDoor()
// washMachine.closeDoor()washMachine.start()
}
WashMachine.kt
/*** 程序员A创建的洗衣机*/
class WashMachine(var module:String,var size:Int){var isDoorOpen = truefun openDoor(){println("洗衣机的门已经打开了...")isDoorOpen = true}fun closeDoor(){println("洗衣机的门已经关闭了...")isDoorOpen = false}fun start(){if (isDoorOpen){println("哔哔...门还没关呢,不能运行")}else {println("放水...")println("水放满了...")println("电机开始转...")println("洗好了...")}}
}
二、升级版洗衣机
Test.kt
/*** 程序员B写的代码* 洗衣服*/
fun main(args:Array<String>){var washMachine = WashMachine("小天鹅",size = 12)washMachine.openDoor()println("小华华把内裤放进去了")washMachine.closeDoor()washMachine.selectMode(1)washMachine.start()
}
WashMachine.kt
/*** 程序员A创建的洗衣机*/
class WashMachine(var module:String,var size:Int){var isDoorOpen = truevar currentMode = 0fun openDoor(){println("洗衣机的门已经打开了...")isDoorOpen = true}fun closeDoor(){println("洗衣机的门已经关闭了...")isDoorOpen = false}fun selectMode(mode:Int){currentMode = modewhen(mode){0 -> println("初始模式,请您选择模式")1 -> println("轻柔")2 -> println("狂揉")else -> println("不要乱拧,拧坏了不保修呀")}}fun start(){if (isDoorOpen){println("哔哔...门还没关呢,不能运行")}else {when(currentMode){0 -> println("选择模式错误,不能开始洗衣服")1 ->{println("放水...")println("轻柔开始,发动机转速 慢")println("洗完啦")}2 -> {println("放水...")println("狂揉开始,发动机转速 快")println("洗完啦")}else ->{println("模式不能被识别")}}}}
}
封装转速模块 private语句类内私有化方法
Test.kt
*** 程序员B写的代码* 洗衣服*/
fun main(args:Array<String>){var washMachine = WashMachine("小天鹅",size = 12)washMachine.openDoor()println("小华华把内裤放进去了")washMachine.closeDoor()washMachine.selectMode(1)washMachine.start()// washMachine.setMotorSpeed(10000)
}
WashMachine.kt
/*** 程序员A创建的洗衣机*/
class WashMachine(var module:String,var size:Int){var isDoorOpen = truevar currentMode = 0fun openDoor(){println("洗衣机的门已经打开了...")isDoorOpen = true}fun closeDoor(){println("洗衣机的门已经关闭了...")isDoorOpen = false}fun selectMode(mode:Int){currentMode = modewhen(mode){0 -> println("初始模式,请您选择模式")1 -> println("轻柔")2 -> println("狂揉")else -> println("不要乱拧,拧坏了不保修呀")}}fun start(){if (isDoorOpen){println("哔哔...门还没关呢,不能运行")}else {when(currentMode){0 -> println("选择模式错误,不能开始洗衣服")1 ->{println("放水...")println("轻柔开始,发动机转速 慢")setMotorSpeed(100)println("洗完啦")}2 -> {println("放水...")println("狂揉开始,发动机转速 快")setMotorSpeed(1000)println("洗完啦")}else ->{println("模式不能被识别")}}}}private fun setMotorSpeed(speed:Int){println("当前发动机转速为${speed}圈/秒")}
}