命令模式
适用场景
优点
缺点
Golang Demo
package command
import (
"fmt"
)
type Command interface {
execute()
}
type Light struct {
name string
}
func NewLight(name string) *Light {
return &Light{name: name}
}
func (l *Light) open() {
fmt.Println("open light " + l.name)
}
func (l *Light) close() {
fmt.Println("close light " + l.name)
}
type OpenLightCommand struct {
light *Light
}
func (o *OpenLightCommand) execute() {
o.light.open()
}
func NewOpenLightCommand(light *Light) *OpenLightCommand {
return &OpenLightCommand{light: light}
}
type CloseLightCommand struct {
light *Light
}
func (c *CloseLightCommand) execute() {
c.light.close()
}
func NewCloseLightCommand(light *Light) *CloseLightCommand {
return &CloseLightCommand{light: light}
}
type App struct {
commandList []Command
}
func NewApp() *App {
return &App{}
}
func (a *App) addCommand(command Command) {
a.commandList = append(a.commandList, command)
}
func (a *App) executeCommand() {
for _, command := range a.commandList {
command.execute()
}
// 清空这个切片
a.commandList = a.commandList[0:0]
}Java Demo
UML

补充另一个版本的Java/Scala Demo 以及源码解析
Java Demo_
Scala Demo
UML_
源码解析
Last updated