设计模式--责任链(Responsibility_Chain)模式
生活随笔
收集整理的這篇文章主要介紹了
设计模式--责任链(Responsibility_Chain)模式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
模式定義
使多個對象都有機會處理請求,從而避免請求的發送者和接受者之間耦合關系,將這些對象連成一條鏈,并沿著這條鏈傳遞請求,直到有一個對象處理它為止
類圖
要點總結
- Chain of Responsibility模式的應用場合在于“一個請求可能有多個接受者,但是最后真正的接受者只有一個”,這時候請求發送者與接受者的耦合有可能出現“變化脆弱”的癥狀,職責鏈的目的就是將二者解耦,從而更好地應對變化
- 應用了Chain of Responsibility模式后,對象的職責分配將更具靈活性,我們可以在運行時動態添加、修改請求的處理職責
- 如果請求傳遞到職責鏈的末尾任得不到處理,應該有一個合理的缺省機制,這也是每一個接受者對象的責任,而不是發出請求的對象的責任
Go語言代碼實現
工程目錄
responsibility_chain.go
package Responsibility_Chainimport "strconv"type Handler interface {Handler(handlerID int) string }type handler struct {name stringnext HandlerhandlerID int }func NewHandler(name string, next Handler, handlerID int) *handler{return &handler{name: name,next: next,handlerID: handlerID,} }func (h *handler) Handler(handlerID int) string{if h.handlerID == handlerID{return h.name + " handled " + strconv.Itoa(handlerID)}return h.next.Handler(handlerID) }responsibility_chain_test.go
package Responsibility_Chainimport ("fmt""testing" )func TestNewHandler(t *testing.T) {wang := NewHandler("laowang", nil, 1)zhang := NewHandler("lanzhang", wang, 2)r := wang.Handler(1)fmt.Println(r)r = zhang.Handler(2)fmt.Println(r) }總結
以上是生活随笔為你收集整理的设计模式--责任链(Responsibility_Chain)模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 设计模式--迭代器(Iterator)模
- 下一篇: 设计模式--命令(Command)模式