命令模式是什么
命令模式是一種行為型設計模式,它可以將一個請求封裝為一個物件,使發出請求的責任和執行請求的責任分割開,這樣兩者之間通過命令物件進行溝通,這樣方便將命令物件進行儲存、傳遞、呼叫、增加與管理,
為什么用命令模式
在軟體開發系統中,“方法的請求者”與“方法的實作者”之間經常存在緊密的耦合關系,這不利于軟體功能的擴展與維護,例如,想對方法進行“撤銷、重做、記錄”等處理都很不方便,因此“如何將方法的請求者與實作者解耦?”變得很重要,命令模式就能很好地解決這個問題,
在現實生活中,命令模式的例子也很多,比如看電視時,我們只需要輕輕一按遙控器就能完成頻道的切換,這就是命令模式,將換臺請求和換臺處理完全解耦了,電視機遙控器(命令發送者)通過按鈕(具體命令)來遙控電視機(命令接收者),
命令模式怎么實作
這里以生活中電視機遙控器(命令發送者)通過按鈕(具體命令)來遙控電視機(命令接收者)來舉例,
device.go (電視設備)
package command
import "fmt"
type device interface {
on()
off()
}
type tv struct {
isRunning bool
}
func (t *tv) on() {
t.isRunning = true
fmt.Println("Turning tv on")
}
func (t *tv) off() {
t.isRunning = false
fmt.Println("Turning tv off")
}
command.go 命令
package command
type command interface {
execute()
}
type onCommand struct {
device device
}
func (c *onCommand) execute() {
c.device.on()
}
type offCommand struct {
device device
}
func (c *offCommand) execute() {
c.device.off()
}
button.go 按鈕
package command
type button struct {
command command
}
func (b *button) press() {
b.command.execute()
}
example.go 客戶端呼叫示例
package command
func Example() {
tv := &tv{}
onCommand := &onCommand{
device: tv,
}
offCommand := &offCommand{
device: tv,
}
onButton := &button{
command: onCommand,
}
onButton.press()
offButton := &button{
command: offCommand,
}
offButton.press()
}
優點
- 單一職責原則, 你可以解耦觸發和執行操作的類,
- 開閉原則, 擴展性良好,增加或洗掉命令非常方便,采用命令模式增加與洗掉命令不會影響其他類,
缺點
- 可能產生大量具體的命令類,因為每一個具體操作都需要設計一個具體命令類,這會增加系統的復雜性,
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/458147.html
標籤:設計模式
