美文网首页设计模式
工厂模式(Factory)

工厂模式(Factory)

作者: 老中医167788 | 来源:发表于2018-11-13 21:20 被阅读0次
    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")
    }
    

    相关文章

      网友评论

        本文标题:工厂模式(Factory)

        本文链接:https://www.haomeiwen.com/subject/kyhrfqtx.html