Go實現設計模式--命令模式

關於命令模式的例子

客戶點單,創造訂單給服務員,服務員將訂單給廚師,廚師烹飪。
用戶使用遙控器,創造命令對象(關電視)給遙控器,遙控對象(電視)關閉。
遙控器代碼的簡單示例:

邏輯關係

實現遙控器,遙控器有插槽,一個插槽對應一個command對象,插槽的下按對應command對象的命令,這樣遙控器不用管這個命令的具體實現,只要調用自己的插槽就可以了。

這裏的command對象對應的是服務員,服務員點單的行爲對應的是命令對象的excute()


type Command interface {
	execute()
}
//點燈
type Light struct{

}

func (p *Light) On() {
	fmt.Println("light on.")
}

//燈的命令
type LightOnCommand struct{
	light Light
}

func (p *LightOnCommand) LightOnCommand(light Light) {
	p.light = light
}

func (p *LightOnCommand) execute() {
	p.light.On()
}

//遙控器
type SimpleRemoteControl struct{
	slot Command

}

func (p *SimpleRemoteControl) setCommand(command Command) {
	p.slot = command
}

func (p *SimpleRemoteControl) buttonWasPressed() {
	p.slot.execute()
}

func main() {
	remote:=new(SimpleRemoteControl)
	light:=new(Light)
	lightOnCo:=new(LightOnCommand)
	lightOnCo.light = *light
	remote.setCommand(lightOnCo)
	remote.buttonWasPressed()
}

整體分析
遙控器內包含命令類
命令類內包含實際對象電燈
這樣遙控器與電燈解耦,只用關注自己調用的是什麼命令類
使用
遙控器調用自己的命令,命令內有具體的命令類對象調用自己對象的接口進行真正的對應操作

定義

命令模式將請求分裝成對象,以便使用不同的請求,隊列或者日誌來參數化其他對象。命令模式也支持可撤銷的操作。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章