【设计模式】第16节:行为型模式之“命令模式”

一、简介

命令模式:将请求(命令)封装为一个对象,这样可以使用不同的请求参数化其他对象(将不同请求依赖注入到其他对象),并且能够支持请求(命令)的排队执行、记录日志、撤销等(附加控制)功能。

二、优点

  • 动作封装
  • 解耦发送者跟接受者
  • 可扩展性
  • 简化和集中错误处理
  • 支持撤销和重做功能
  • 易于实现组合命令

三、UML类图

四、案例

家里有很多房间,有卧室和厨房等,用一套灯光管理系统同一管理所有灯的开关。

go 复制代码
package main

import "fmt"

type Light interface {
	On()
	Off()
}

type KitchenLight struct {
}

func NewKitchenLight() *KitchenLight {
	return &KitchenLight{}
}

func (*KitchenLight) On() {
	fmt.Println("Kitchen light is on")
}

func (*KitchenLight) Off() {
	fmt.Println("Kitchen light is off")
}

type LivingRoomLight struct {
}

func NewLivingRoomLight() *LivingRoomLight {
	return &LivingRoomLight{}
}

func (*LivingRoomLight) On() {
	fmt.Println("Living room light is on")
}

func (*LivingRoomLight) Off() {
	fmt.Println("Living room light is off")
}

type Command interface {
	Execute()
	Undo()
}

type LightOnCommand struct {
	Lights []Light
}

func NewLightOnCommand(lights []Light) LightOnCommand {
	return LightOnCommand{Lights: lights}
}

func (loc *LightOnCommand) Execute() {
	for _, light := range loc.Lights {
		light.On()
	}
}

func (loc *LightOnCommand) Undo() {
	for _, light := range loc.Lights {
		light.Off()
	}
}

type LightOffCommand struct {
	Lights []Light
}

func NewLightOffCommand(lights []Light) LightOffCommand {
	return LightOffCommand{Lights: lights}
}

func (loc *LightOffCommand) Execute() {
	for _, light := range loc.Lights {
		light.Off()
	}
}

func (loc *LightOffCommand) Undo() {
	for _, light := range loc.Lights {
		light.On()
	}
}

func main() {
	kitchenLight := NewKitchenLight()
	livingRoomLight := NewLivingRoomLight()

	lightOnCommand := NewLightOnCommand([]Light{kitchenLight, livingRoomLight})
	lightOnCommand.Execute()
	lightOnCommand.Undo()

	lightOffCommand := NewLightOffCommand([]Light{kitchenLight, livingRoomLight})
	lightOffCommand.Execute()
	lightOffCommand.Undo()
}

五、对比

命令模式与策略模式的区别:在策略模式中,不同的策略具有相同的目的、不同的实现、互相之间可以替换。比如,BubbleSort、SelectionSort都是为了实现排序的,只不过一个是用冒泡排序算法来实现的,另一个是用选择排序算法来实现的。而在命令模式中,不同的命令具有不同的目的,对应不同的处理逻辑,并且互相之间不可替换。

相关推荐
七月丶12 小时前
别再手动凑 PR 了:这个 AI Skill 会按仓库习惯自动建分支、拆提交、提 PR
人工智能·设计模式·程序员
刀法如飞12 小时前
从程序员到架构师:6大编程范式全解析与实践对比
设计模式·系统架构·编程范式
九狼13 小时前
Flutter + Riverpod +MVI 架构下的现代状态管理
设计模式
静水流深_沧海一粟1 天前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder1 天前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
阿星AI工作室2 天前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式
_哆啦A梦2 天前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding
阿闽ooo5 天前
中介者模式打造多人聊天室系统
c++·设计模式·中介者模式
小米4966 天前
js设计模式 --- 工厂模式
设计模式
逆境不可逃6 天前
【从零入门23种设计模式08】结构型之组合模式(含电商业务场景)
线性代数·算法·设计模式·职场和发展·矩阵·组合模式