一、命令相关类
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)
}
三、运行结果