设计模式

工厂模式(Factory)

2018-11-13  本文已影响0人  老中医167788
abstract class Operation{
    var firstNumber:Float = 0f
    var lastNumber:Float = 0f
    abstract fun getResult():Float
}

class OperationAdd : Operation(){
    override fun getResult(): Float = firstNumber + lastNumber
}

class OperationSub : Operation(){
    override fun getResult(): Float = firstNumber - lastNumber
}

class OperationFactory{
    companion object{
        fun createOperation(operate:String):Operation?{
            when(operate){
                "+" -> return OperationAdd()
                "-" -> return OperationSub()
                else-> return null
            }
        }
    }
}

fun main(args:Array<String>){
    var operation = OperationFactory.createOperation("+")
    operation?.firstNumber = 10f
    operation?.lastNumber = 10f
    var result:Float = operation?.getResult()!!

    println("result is: $result")
}
上一篇下一篇

猜你喜欢

热点阅读