2023-08-23|閱讀時間 ‧ 約 3 分鐘

Golang - Design Pattern #5: 命令模式 (Command)

raw-image


命令模式:就像你的智能家居遙控器!

你有沒有用過智能家居遙控器,按一下開燈、再按一下關電視?那麼,你可能已經用過命令模式了!


命令模式到底是啥?

想像命令模式就像是你的遙控器上的一堆按鈕。每個按鈕都是一個命令,當你按下去,某些事情就會發生。你不必知道背後的具體工作原理,只需要知道按這個就能開燈,按那個就能關電視。

不囉嗦,直接看看程式碼

package main

import "fmt"

// Command 是命令的接口
type Command interface {
Execute()
}

// 開燈 Command​
type LightOnCommand struct {
Light *Light
}

func (l *LightOnCommand) Execute() {
l.Light.TurnOn()
}

// 關燈 Command
type LightOffCommand struct {
Light *Light
}

func (l *LightOffCommand) Execute() {
l.Light.TurnOff()
}

// 燈​
type Light struct{}

// 開燈
func (l *Light) TurnOn() {
fmt.Println("燈亮了!")
}

// 關燈
func (l *Light) TurnOff() {
fmt.Println("燈熄了!")
}

// Remote 遙控器
type Remote struct {
Command Command
}

func (r *Remote) PressButton() {
r.Command.Execute()
}

func main() {
light := &Light{}
lightOn := &LightOnCommand{Light: light}
lightOff := &LightOffCommand{Light: light}

remote := &Remote{}

remote.Command = lightOn
remote.PressButton()

remote.Command = lightOff
remote.PressButton()
}

這個程式碼展示了一個簡單的燈和遙控器。你可以按遙控器的按鈕來開燈或關燈,不必知道它背後是怎麼工作的。


總結

命令模式就像是我們生活中的遙控器,使我們的生活變得更加便利。在程式設計中,它可以幫助我們更好地組織和管理代碼,使我們的系統更加模組化和靈活。所以下次當你拿起遙控器時,也許會想到這背後的命令模式哦!

分享至
成為作者繼續創作的動力吧!
歡迎來到 Golang Lab!我們專注於提供深入的 Golang 學習體驗。透過系列文、實例項目和進階指南,探索從基礎到進階的開發技巧,包括正則表達式、併發程式設計、性能優化等。無論您是新手還是有經驗的開發者,我們都致力於協助您迅速掌握 Golang,並在實際應用中取得成功。一同學習、分享和成長!
© 2024 vocus All rights reserved.