当前位置:   article > 正文

Kotlin中常用的设计模式整理_kotlin partial function

kotlin partial function

Kotlin 中设计模式有很多种写法,各有个的好处,这里不是统一

工厂模式

Kotlin 中 object 是天生的单例,同时通过伴生对象的语法来创建。,伴生对象也支持扩展函数。

  1. interface Computer {
  2. val cpu: String
  3. //增加Factory名字
  4. companion object Factory {
  5. operator fun invoke(type: ComputerType): Computer {
  6. return when (type) {
  7. ComputerType.PC -> PC()
  8. ComputerType.SERVER -> Server()
  9. }
  10. }
  11. }
  12. }
  13. class PC(override val cpu: String = "Core") : Computer
  14. class Server(override val cpu: String = "Xeon") : Computer
  15. enum class ComputerType {
  16. PC, SERVER
  17. }
  18. //调用
  19. fun main(args: Array<String>) {
  20. Computer.Factory(ComputerType.PC)
  21. }

内联函数的一大特征是可以获取具体的参数类型,实现在抽象工厂上,可以创建一个泛型类对象。

  1. abstract class AbstractFactory {
  2. abstract fun produce(): Computer
  3. companion object {
  4. //普通,调用方式
  5. // val abstractFactory = AbstractFactory(DellFartory())
  6. // val produce = abstractFactory.produce()
  7. operator fun invoke(factory: AbstractFactory): AbstractFactory {
  8. return factory
  9. }
  10. //简化,调用方式
  11. // val abstractFactory = AbstractFactory<Dell>()
  12. // val produce = abstractFactory.produce()
  13. inline operator fun <reified T : Computer> invoke(): AbstractFactory = when (T::class) {
  14. Dell::class -> DellFartory()
  15. Asus::class -> AsusFartory()
  16. Acer::class -> AcerFartory()
  17. else -> throw IllegalAccessException()
  18. }
  19. }
  20. }

构建者模式

Kotlin 中可选参数完全可以替代 Java 的 build 模式,可以利用类的原生特性来规避构造参数过长问题,重点是可以利用 require 方法对参数的值进行约束。

  1. //解决Java构建者模式代码过长
  2. // Robot(code = "007")
  3. class Robot(
  4. val code: String,
  5. val battery: String? = null,
  6. val height: Int? = null,
  7. val weight: Int? = null
  8. ) {
  9. init {
  10. //解决Java构建者模式 build() 判断
  11. require(weight == null || battery == null) {
  12. "weight and battery is not null"
  13. }
  14. }
  15. }

观察者模式

Kotlin 标准库支持 observable 委托属性,比 Java 更加灵活

  1. import kotlin.properties.Delegates
  2. import kotlin.reflect.KProperty
  3. class StockUpdate {
  4. val listeners = mutableListOf<StockUpdateListener>()
  5. //委托属性的元数据 KProperty 对象、旧值、新值
  6. var price: Int by Delegates.observable(0) { property, oldValue, newValue ->
  7. listeners.forEach {
  8. if (newValue != oldValue) {
  9. it.onRise(price)
  10. } else {
  11. it.onFall(price)
  12. }
  13. }
  14. }
  15. }
  16. class StockDisplay : StockUpdateListener {
  17. override fun onRise(price: Int) {
  18. TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
  19. }
  20. override fun onFall(price: Int) {
  21. TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
  22. }
  23. }
  24. interface StockUpdateListener {
  25. fun onRise(price: Int)
  26. fun onFall(price: Int)
  27. }
  28. //源码
  29. public inline fun <T> observable(initialValue: T, crossinline onChange: (property: KProperty<*>, oldValue: T, newValue: T) -> Unit):
  30. ReadWriteProperty<Any?, T> =
  31. object : ObservableProperty<T>(initialValue) {
  32. override fun afterChange(property: KProperty<*>, oldValue: T, newValue: T) = onChange(property, oldValue, newValue)
  33. }

策略模式

高阶函数的简化版,抽象算法。

  1. class Swimmer(val swimming: () -> Unit) {
  2. fun swim() {
  3. swimming()
  4. }
  5. }
  6. fun a1() {
  7. }
  8. fun a2() {
  9. }
  10. fun main(args: Array<String>) {
  11. val swimmer = Swimmer(::a1)
  12. swimmer.swim()
  13. val swimmer2 = Swimmer(::a2)
  14. swimmer2.swim()
  15. }

模板方法模式

高阶函数的简化版,替代继承实现。

  1. //高阶函数代替继承
  2. class CivicCenterTask {
  3. fun execute(askForHelp: () -> Unit) {
  4. this.lineUp()
  5. askForHelp()
  6. this.evaluate()
  7. }
  8. private fun lineUp() {
  9. }
  10. private fun evaluate() {
  11. }
  12. }
  13. fun pullSocialSecurity() {
  14. }
  15. fun main(args: Array<String>) {
  16. val civicCenterTask = CivicCenterTask()
  17. civicCenterTask.execute(::pullSocialSecurity)
  18. }

迭代器模式

  1. data class Bc(val name: String)
  2. class Bd(val bcs: List<Bc>) {
  3. operator fun iterator(): Iterator<Bc> = this.bcs.iterator()
  4. }
  5. fun main(args: Array<String>) {
  6. //便捷遍历
  7. val bd = Bd(listOf())
  8. for (bc in bd) {
  9. println(bc)
  10. }
  11. }

责任链模式

基于偏函数的责任链模式语法,通过中缀表达式的形式,结合 orElse 方法

  1. /*
  2. 声明类对象时需要接受两个构造参数,其中 definetAt 为校验函数, f 为处理函数
  3. 当 PartialFunction 类对象执行 invoke 方法时,definetAt 会输入参数 p1 进行有效校验
  4. 如果校验结果通过,则执行 f 函数,同时将 p1 作为参数传毒给它,反之抛出异常
  5. */
  6. class PartialFunction<in P1, out R>(
  7. private val definetAt: (P1) -> Boolean,
  8. private val f: (P1) -> R
  9. ) : (P1) -> R {
  10. override fun invoke(p1: P1): R {
  11. if (definetAt(p1)) {
  12. return f(p1)
  13. } else {
  14. throw IllegalAccessException()
  15. }
  16. }
  17. fun isDefinedAt(p1: P1) = definetAt(p1)
  18. }
  19. /**
  20. * orElse 方法种可以传入另一个 PartialFunction 类对象 that,它也就是责任链模式中的后继者
  21. * infix 关键字让 orElse 成为一个中缀函数,从而让责任链调用的语法变得更加直观
  22. */
  23. infix fun <P1, R> PartialFunction<P1, R>.orElse(that: PartialFunction<P1, R>): PartialFunction<P1, R> {
  24. return PartialFunction({
  25. this.isDefinedAt(it) || that.isDefinedAt(it)
  26. }) {
  27. when {
  28. this.isDefinedAt(it) -> this(it)
  29. else -> that(it)
  30. }
  31. }
  32. }
  33. data class ApplyEvent(val money: Int, val title: String)
  34. val groupLeader = {
  35. val definetAt: (ApplyEvent) -> Boolean = { it.money <= 200 }
  36. val handler: (ApplyEvent) -> Unit = { println(" groupLeader ... ") }
  37. PartialFunction(definetAt, handler)
  38. }()
  39. val president = {
  40. val definetAt: (ApplyEvent) -> Boolean = { it.money <= 500 }
  41. val handler: (ApplyEvent) -> Unit = { println(" president ... ") }
  42. PartialFunction(definetAt, handler)
  43. }()
  44. val college = {
  45. val definetAt: (ApplyEvent) -> Boolean = { true }
  46. val handler: (ApplyEvent) -> Unit = { println(" college ... ") }
  47. PartialFunction(definetAt, handler)
  48. }()
  49. fun main(args: Array<String>) {
  50. val appChain = groupLeader orElse president orElse college
  51. }

装饰着模式

依靠类委托的语法实现。

  1. interface MacBook {
  2. fun getCost(): Int
  3. }
  4. class MacBookPro : MacBook {
  5. override fun getCost(): Int = 10
  6. }
  7. class ProcessorUpgradeMacbookPor(val macBook: MacBook) : MacBook by macBook {
  8. override fun getCost(): Int = macBook.getCost() + 20
  9. }
  10. fun main(args: Array<String>) {
  11. var macBookPro = MacBookPro()
  12. var processorUpgradeMacbookPor = ProcessorUpgradeMacbookPor(macBookPro)
  13. processorUpgradeMacbookPor.getCost()
  14. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/天景科技苑/article/detail/752236
推荐阅读
相关标签
  

闽ICP备14008679号