20_命令模式

一、命令相关类

package com.study.command

/**
 * 命令行模式
 */
abstract class Command {
    /**
     * 执行命令
     */
    abstract fun doit()

    /**
     * 不执行命令
     */
    abstract fun undo()
}
package com.study.command

/**
 * 删除命令
 */
class DeleteCommand(var content: Content) : Command() {
    var delete: String = ""
    override fun doit() {
        delete = content.content.substring(0, 5)
        content.content = content.content.substring(5)
    }

    override fun undo() {
        content.content = delete + content.content
    }
}
package com.study.command

/**
 * 插入命令
 */
class InsertCommand(var content: Content) : Command() {
    val target = "伟大复兴"

    override fun doit() {
        content.content = "${content.content}$target"
    }

    override fun undo() {
        content.content = content.content.substring(0, content.content.length - target.length)
    }
}
package com.study.command

/**
 * 更新命令
 */
class UpdateCommand(var content: Content) : Command() {
    val target = "东方红";

    override fun doit() {
        content.content = content.content.replace("中国红", target)
    }

    override fun undo() {
        content.content.replace(target, "中国红")
    }
}

二、主程序调用

package com.study.command


/**
 *
定义和类型
定义:将“请求”封装成对象,以便使用不同的请求
命令模式解决了应用程序中的对象的职责以及他们之间的通信方式

类型:行为型
适用场景
请求调用者和请求接收者需要解耦,使得调用者和接收者不直接交互
需要抽象出等待执行的行为

优点
降低耦合
容易扩展新命令或者一组命令

缺点
命令的无限扩展会增加类的数量,提高系统实现复杂度
 *
 */
fun main() {
    var content = Content("中国的中国红,我和我的祖国")

    val insertCommand = InsertCommand(content)
    val updateCommand = UpdateCommand(content)
    val deleteCommand = DeleteCommand(content)


    val commands = arrayListOf<Command>()
    commands.add(insertCommand)
    commands.add(updateCommand)
    commands.add(deleteCommand)
    //执行命令
    for (command in commands) {
        println("========================${commands.indexOf(command)}")
        command.doit()
        println(content.content)
    }
    println(content.content)

    //退回刚刚的执行,回到最初始的状态
    for (i in commands.lastIndex downTo 0) {
        commands[i].undo()
    }
    println(content.content)
}

三、运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值