Kotlin 设计模式-命令

来源:互联网 发布:人工智能教学百度云 编辑:程序博客网 时间:2024/05/21 11:20

前言

在软件系统中,“行为请求者”与“行为实现者”通常呈现一种“紧耦合”。但在某些场合,比如要对行为进行“记录、撤销/重做、事务”等处理,这种无法抵御变化的紧耦合是不合适的。在这种情况下,如何将“行为请求者”与“行为实现者”解耦?将一组行为抽象为对象,实现二者之间的松耦合。这就是命令模式(Command Pattern)。

摘自 百度百科-命令模式
简单来说就是将一个命令(行为)封装为一个对象,使用者可以根据当前传入的对象,进行不同的操作。类似于电脑根据用户输入的指令进行运算的行为。

Kotlin中的命令模式

没有特别对命令模式的优化方案,所以写法和Java 中的命令模式相同,但是kotlin中的继承,实现写法和Java中的不同,在此处提出来说一下。
在Java 中继承和实现是使用的两个不同的关键字,集成使用extends而实现使用implements。
在Kotlin中继承和实现使用的是相同的符号:(冒号)。
冒号在Kotlin中,总体上说,是用来标注参数类型、方法返回值类型、类的继承和实现这集中地方使用。

  • 参数类型使用(有类型推导,使用的地方大多数是注入时标注类型):
var id:Int = 1
  • 方法返回值
fun foo():Int {    return 1}
  • 类的集成与实现
class Student : Person(),Study

Student 继承 Person类,实现Study接口

show me code

interface OrderCommand {    fun execute()}class OrderAddCommand(val id: Long) : OrderCommand {    override fun execute() = println("adding order with id: $id")}class OrderPayCommand(val id: Long) : OrderCommand {    override fun execute() = println("paying for order with id: $id")}class CommandProcessor {    private val queue = ArrayList<OrderCommand>()    fun addToQueue(orderCommand: OrderCommand): CommandProcessor            = apply { queue.add(orderCommand) }    fun processCommands(): CommandProcessor = apply {        queue.forEach { it.execute() }        queue.clear()    }}

调用代码

CommandProcessor()    .addToQueue(OrderAddCommand(1L))    .addToQueue(OrderAddCommand(2L))    .addToQueue(OrderPayCommand(2L))    .addToQueue(OrderPayCommand(1L))    .processCommands()
原创粉丝点击