kotlin|kotlin 简单工厂实现

【kotlin|kotlin 简单工厂实现】1) 创建名称为 Api 的接口

interface Api { fun opreator() }

  1. 创建几个实现Api接口的类
class ImpA :Api{ override fun opreator() { System.out.println("我是ImpA") } }class ImpB:Api { override fun opreator() { System.out.print("我是ImpB") } }

  1. 创建工厂
object Factory {/** * 选择生成那个类 * @param which 控制生成的类 */ fun getApi(which:Int):Api{ var api:Api when(which){ 1->{ api = ImpA()} 2->{ api = ImpB()} else ->{ api = ImpC() } } return api } /** * 选择生成那个类 * @param java */ fun apiProduct(java: Class): T {var api:Api = java.newInstance()return api as T } }

  1. 测试用例
class ExampleUnitTest { @Test funapiFactoryTest(){ val api = Factory.getApi(1) api.opreator()val api2 = Factory.apiProduct(ImpB::class.java) api2.opreator()val api3 = Factory.apiProduct(ImpC::class.java) api3.opreator() } }

    推荐阅读