1) 創(chuàng)建名稱(chēng)為 Api 的接口
interface Api {
fun opreator()
}
- 創(chuàng)建幾個(gè)實(shí)現(xiàn)Api接口的類(lèi)
class ImpA :Api{
override fun opreator() {
System.out.println("我是ImpA")
}
}
class ImpB:Api {
override fun opreator() {
System.out.print("我是ImpB")
}
}
- 創(chuàng)建工廠(chǎng)
object Factory {
/**
* 選擇生成那個(gè)類(lèi)
* @param which 控制生成的類(lèi)
*/
fun getApi(which:Int):Api{
var api:Api
when(which){
1->{ api = ImpA()}
2->{ api = ImpB()}
else ->{ api = ImpC() }
}
return api
}
/**
* 選擇生成那個(gè)類(lèi)
* @param java
*/
fun <T:Api> apiProduct(java: Class<T>): T {
var api:Api = java.newInstance()
return api as T
}
}
- 測(cè)試用例
class ExampleUnitTest {
@Test
fun apiFactoryTest(){
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()
}
}