工厂模式
引言

实现
简单工厂
abstract class ISimple {
}
class SimpleA: ISimple() {
}
class SimpleB: ISimple() {
}
object SimpleFactory {
fun create(tag: String): ISimple {
return when(tag) {
TAG_A -> SimpleA()
TAG_B -> SimpleB()
else -> SimpleA()
}
}
}
const val TAG_A = "TAG_A"
const val TAG_B = "TAG_B"
抽象工厂
interface IAnimal {
fun eat()
}
class Dog: IAnimal {
override fun eat() {
LogTool.i("Dog eat")
}
}
interface IAnimalFactory {
fun <T : IAnimal?> creator(clazz: Class<T>?): IAnimal?
}
class AnimalFactory: IAnimalFactory {
override fun <T : IAnimal?> creator(clazz: Class<T>?): IAnimal? {
var animal: IAnimal? = null
if (clazz == null) {
throw IllegalArgumentException("class must not null")
} else {
try {
animal = clazz.newInstance()
} catch (e: InstantiationException) {
LogTool.e("InstantiationException: ${e.message}")
} catch (e: IllegalAccessException) {
LogTool.e("IllegalAccessException: ${e.message}")
}
}
return animal
}
}
object AnimalTest {
fun createDog(): IAnimal? {
val ac = AnimalFactory()
return ac.creator(Dog::class.java)
}
}