工厂方法模式介绍

我们在开发的过程中,经常会遇到在我们之前的方法上添加很多新的需求,如果这里用工厂模式的话,那么我们只需要增加我们的新的工厂类就可以了,不需要修改之前的代码。

话不多说,我这里只是用的一个简单的例子。

首先定义一个工厂接口(里面有俩个方法)

interface FactoryInterface {
    fun shows():String
    fun getAge() : Int
}

然后新建一个类(工厂管理员)实现工厂接口

class FactoryManager : FactoryInterface {
    override fun getAge(): Int {
        return 1
    }
    override fun shows(): String {
        return "我是A"
    }
    companion object {
        private var instance:FactoryManager?=null
        @Synchronized
        fun getInstances():FactoryManager{
            if (instance == null){
                instance = FactoryManager()
            }
            return instance!!
        }
    }
}

然后新建一个工厂提供者接口

interface FactoryProvider {
    fun sends():FactoryInterface
    fun sendInts():FactoryInterface
}

然后我们自己的提供者实现工厂提供者这个接口

class MyProviders : FactoryProvider{
    override fun sendInts(): FactoryInterface {
        return FactoryManager.getInstances()
    }
    override fun sends(): FactoryInterface {
        return FactoryManager.getInstances()
    }
    companion object {
        private var instance : MyProviders?=null
        @Synchronized
        fun getInstance():MyProviders{
            if (instance == null){
                instance = MyProviders()
            }
            return instance!!
        }
    }
}

然后使用

    private fun inits() {
        btn_gongchang.setOnClickListener {
            val A_shows = MyProviders.getInstance().sends().shows()
            val agea = MyProviders.getInstance().sendInts().getAge()
            tvs.setText(A_shows+agea)
        }
    }

这样我们再增加一个新的需求的时候,代码无需更改太多,只需要更改接口增加方法,就ok。

原文的uri地址https://www.cnblogs.com/geek6/p/3951677.html

猜你喜欢

转载自blog.csdn.net/mintent/article/details/86147599