赞
踩
Kotlin 中设计模式有很多种写法,各有个的好处,这里不是统一
工厂模式
Kotlin 中 object 是天生的单例,同时通过伴生对象的语法来创建。,伴生对象也支持扩展函数。
- interface Computer {
- val cpu: String
-
- //增加Factory名字
- companion object Factory {
- operator fun invoke(type: ComputerType): Computer {
- return when (type) {
- ComputerType.PC -> PC()
- ComputerType.SERVER -> Server()
- }
- }
- }
- }
-
- class PC(override val cpu: String = "Core") : Computer
- class Server(override val cpu: String = "Xeon") : Computer
-
- enum class ComputerType {
- PC, SERVER
- }
-
- //调用
- fun main(args: Array<String>) {
- Computer.Factory(ComputerType.PC)
- }
内联函数的一大特征是可以获取具体的参数类型,实现在抽象工厂上,可以创建一个泛型类对象。
- abstract class AbstractFactory {
- abstract fun produce(): Computer
-
- companion object {
- //普通,调用方式
- // val abstractFactory = AbstractFactory(DellFartory())
- // val produce = abstractFactory.produce()
- operator fun invoke(factory: AbstractFactory): AbstractFactory {
- return factory
- }
-
- //简化,调用方式
- // val abstractFactory = AbstractFactory<Dell>()
- // val produce = abstractFactory.produce()
- inline operator fun <reified T : Computer> invoke(): AbstractFactory = when (T::class) {
- Dell::class -> DellFartory()
- Asus::class -> AsusFartory()
- Acer::class -> AcerFartory()
- else -> throw IllegalAccessException()
- }
- }
- }
构建者模式
Kotlin 中可选参数完全可以替代 Java 的 build 模式,可以利用类的原生特性来规避构造参数过长问题,重点是可以利用 require 方法对参数的值进行约束。
- //解决Java构建者模式代码过长
- // Robot(code = "007")
- class Robot(
- val code: String,
- val battery: String? = null,
- val height: Int? = null,
- val weight: Int? = null
- ) {
- init {
- //解决Java构建者模式 build() 判断
- require(weight == null || battery == null) {
- "weight and battery is not null"
- }
- }
- }
观察者模式
Kotlin 标准库支持 observable 委托属性,比 Java 更加灵活
- import kotlin.properties.Delegates
- import kotlin.reflect.KProperty
-
- class StockUpdate {
- val listeners = mutableListOf<StockUpdateListener>()
-
- //委托属性的元数据 KProperty 对象、旧值、新值
- var price: Int by Delegates.observable(0) { property, oldValue, newValue ->
- listeners.forEach {
- if (newValue != oldValue) {
- it.onRise(price)
- } else {
- it.onFall(price)
- }
- }
- }
- }
-
- class StockDisplay : StockUpdateListener {
- override fun onRise(price: Int) {
- TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
- }
-
- override fun onFall(price: Int) {
- TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
- }
- }
-
- interface StockUpdateListener {
- fun onRise(price: Int)
- fun onFall(price: Int)
- }
-
- //源码
- public inline fun <T> observable(initialValue: T, crossinline onChange: (property: KProperty<*>, oldValue: T, newValue: T) -> Unit):
- ReadWriteProperty<Any?, T> =
- object : ObservableProperty<T>(initialValue) {
- override fun afterChange(property: KProperty<*>, oldValue: T, newValue: T) = onChange(property, oldValue, newValue)
- }
策略模式
高阶函数的简化版,抽象算法。
- class Swimmer(val swimming: () -> Unit) {
- fun swim() {
- swimming()
- }
- }
-
- fun a1() {
- }
-
- fun a2() {
- }
-
- fun main(args: Array<String>) {
- val swimmer = Swimmer(::a1)
- swimmer.swim()
- val swimmer2 = Swimmer(::a2)
- swimmer2.swim()
- }
模板方法模式
高阶函数的简化版,替代继承实现。
- //高阶函数代替继承
- class CivicCenterTask {
- fun execute(askForHelp: () -> Unit) {
- this.lineUp()
- askForHelp()
- this.evaluate()
- }
-
- private fun lineUp() {
- }
-
- private fun evaluate() {
- }
- }
-
- fun pullSocialSecurity() {
- }
-
- fun main(args: Array<String>) {
- val civicCenterTask = CivicCenterTask()
- civicCenterTask.execute(::pullSocialSecurity)
- }
迭代器模式
- data class Bc(val name: String)
- class Bd(val bcs: List<Bc>) {
- operator fun iterator(): Iterator<Bc> = this.bcs.iterator()
- }
-
- fun main(args: Array<String>) {
- //便捷遍历
- val bd = Bd(listOf())
- for (bc in bd) {
- println(bc)
- }
- }
责任链模式
基于偏函数的责任链模式语法,通过中缀表达式的形式,结合 orElse 方法
- /*
- 声明类对象时需要接受两个构造参数,其中 definetAt 为校验函数, f 为处理函数
- 当 PartialFunction 类对象执行 invoke 方法时,definetAt 会输入参数 p1 进行有效校验
- 如果校验结果通过,则执行 f 函数,同时将 p1 作为参数传毒给它,反之抛出异常
- */
- class PartialFunction<in P1, out R>(
- private val definetAt: (P1) -> Boolean,
- private val f: (P1) -> R
- ) : (P1) -> R {
- override fun invoke(p1: P1): R {
- if (definetAt(p1)) {
- return f(p1)
- } else {
- throw IllegalAccessException()
- }
- }
-
- fun isDefinedAt(p1: P1) = definetAt(p1)
- }
-
- /**
- * orElse 方法种可以传入另一个 PartialFunction 类对象 that,它也就是责任链模式中的后继者
- * infix 关键字让 orElse 成为一个中缀函数,从而让责任链调用的语法变得更加直观
- */
- infix fun <P1, R> PartialFunction<P1, R>.orElse(that: PartialFunction<P1, R>): PartialFunction<P1, R> {
- return PartialFunction({
- this.isDefinedAt(it) || that.isDefinedAt(it)
- }) {
- when {
- this.isDefinedAt(it) -> this(it)
- else -> that(it)
- }
- }
- }
-
- data class ApplyEvent(val money: Int, val title: String)
-
- val groupLeader = {
- val definetAt: (ApplyEvent) -> Boolean = { it.money <= 200 }
- val handler: (ApplyEvent) -> Unit = { println(" groupLeader ... ") }
- PartialFunction(definetAt, handler)
- }()
-
- val president = {
- val definetAt: (ApplyEvent) -> Boolean = { it.money <= 500 }
- val handler: (ApplyEvent) -> Unit = { println(" president ... ") }
- PartialFunction(definetAt, handler)
- }()
-
- val college = {
- val definetAt: (ApplyEvent) -> Boolean = { true }
- val handler: (ApplyEvent) -> Unit = { println(" college ... ") }
- PartialFunction(definetAt, handler)
- }()
-
- fun main(args: Array<String>) {
-
- val appChain = groupLeader orElse president orElse college
- }
装饰着模式
依靠类委托的语法实现。
- interface MacBook {
- fun getCost(): Int
- }
-
- class MacBookPro : MacBook {
- override fun getCost(): Int = 10
- }
-
- class ProcessorUpgradeMacbookPor(val macBook: MacBook) : MacBook by macBook {
- override fun getCost(): Int = macBook.getCost() + 20
- }
-
- fun main(args: Array<String>) {
- var macBookPro = MacBookPro()
- var processorUpgradeMacbookPor = ProcessorUpgradeMacbookPor(macBookPro)
- processorUpgradeMacbookPor.getCost()
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。