定义
命令模式(Command Pattern)是一种数据驱动的设计模式,它属于行为型模式。请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令。相信大家看完这段文字一头雾水。
包括三个核心对象
1、调用者(Invoker):持有一个命令对象,并在某个时间点调用命令对象的execute()方法。
2、命令对象(Command):持有一个接收者,和一个execute()方法,在execute中执行接收者的动作。
3、接收者(Receiver):动作的执行者。
下面以遥控器为例来演示命令模式,给遥控器的多对开关按钮设置不同的功能,比如:打开关闭卧室的灯,打开关闭卫生间的灯。将遥控器与灯分离,松耦合设计,通过创建命令对象的方式将二者关联。遥控器持有开灯或者关灯的命令对象,按下按钮触发命令对象执行命令(灯作为接收者真正执行开灯关灯的动作)。
receiver
class Reciver {
fun on(){
System.out.println("on ")
}
fun off(){
System.out.println("off ")
}
}
command
interface Command {
fun excute()
}
class LightOnCommand():Command{
val light = Reciver()
override fun excute(){
light.on()
}
}
class LightOffCommand():Command{
val light = Reciver()
override fun excute(){
light.off()
}
}
invoker
class Remoter {
val onCommand = LightOnCommand()
val offCommand = LightOffCommand()
open fun offRemote(){
offCommand.excute()
}
open fun onRemote(){
onCommand.excute()
}
}
client
class Client {
companion object{
@JvmStatic
fun main(arges:Array<String>){
val remoter = Remoter()
remoter.offRemote();
remoter.onRemote();
}
}
}
总结
隔离执行者和操纵者,通过命令来隔离开来。