跟我一起学“仓颉”设计模式-命令模式练习题
一、练习题1. 设计一个简易的加法运算器该运算器可以实现简易的加法还可以对运算执行撤销操作。类图核心代码package DesignPattern.command // 接收者 public class Add { private var num: Int64 0 public func add(value: Int64) { num value return num } } // 抽象命令类 public abstract class AbstructCommand { public func execute(value: Int64): Int64 public func undo(): Int64 } // 具体命令类 public class AddCommand : AbstructCommand { private var value: Int64 0 private let add: Add Add() public func execute(value: Int64): Int64 { this.value value return add.add(value) } public func undo(): Int64 { return add.add(-this.value) } } public class Btn { private var command OptionAbstructCommand.None public func setCommand(command: AbstructCommand) { this.command command } public func sum(value: Int64) { let result command.getOrThrow().execute(value) println(加法运算结果为: ${result}) } public func undo() { let result command.getOrThrow().undo() println(撤销运算结果为: ${result}) } }测试代码package DesignPattern import DesignPattern.command.* main(): Int64 { let btn Btn() btn.setCommand(AddCommand()) btn.sum(22) btn.sum(8) btn.sum(10) btn.undo() return 0 }二、小结本章为大家详细的介绍了仓颉设计模式中命令模式练习题的内容下一章为大家带来解释器模式的内容。最后创作不易如果大家觉得我的文章对学习仓颉设计模式有帮助的话就动动小手点个免费的赞吧收到的赞越多我的创作动力也会越大哦谢谢大家