设计模式--访问器(Visitor)模式
生活随笔
收集整理的這篇文章主要介紹了
设计模式--访问器(Visitor)模式
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
模式定義
表示一個(gè)作用于某對(duì)象結(jié)構(gòu)中的各元素的操作,使得可以在不改變(穩(wěn)定)各元素的類的前提下定義(擴(kuò)展)作用于這些元素的新操作(變化)
類圖
要點(diǎn)總結(jié)
- Visitor模式通過所謂雙重分發(fā)(double dispatch)來實(shí)現(xiàn)在不更改(不添加新的操作-編譯時(shí))Element類層次結(jié)構(gòu)的前提下,在運(yùn)行時(shí)透明地為類層次結(jié)構(gòu)上的各個(gè)類動(dòng)態(tài)添加新的操作(支持變化)
- 所謂雙重分發(fā)即Visitor模式中間包括了兩個(gè)多態(tài)分發(fā):第一個(gè)為accept方法的多態(tài)辨析,第二個(gè)為visitElementX方法的多態(tài)辨析
- Visitor模式的最大缺點(diǎn)在于擴(kuò)展類層次結(jié)構(gòu)(增加新的Element子類),會(huì)導(dǎo)致Visitor類的改變,因此Visitor模式適用于“Element類層次結(jié)構(gòu)穩(wěn)定,而其中的操作卻經(jīng)常面臨頻繁改動(dòng)”
Go語言代碼實(shí)現(xiàn)
工程目錄
visitor.go
package Visitorimport "fmt"type IVisitor interface {Visit() }type WeiBoVisitor struct {}func (w WeiBoVisitor) Visit(){fmt.Println("Visit WeiBo") }type IQIYIVisitor struct {}func (i IQIYIVisitor) Visit () {fmt.Println("Visit IQiYi") }type IElement interface {Accept(visitor IVisitor) }type Element struct {}func (e Element) Accept(v IVisitor) {v.Visit() }visitor_test.go
package Visitorimport "testing"func TestElement_Accept(t *testing.T) {e := new(Element)e.Accept(new(WeiBoVisitor))e.Accept(new(IQIYIVisitor)) }總結(jié)
以上是生活随笔為你收集整理的设计模式--访问器(Visitor)模式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 设计模式--命令(Command)模式
- 下一篇: 设计模式--解析器(Interprete