13.Golang設(shè)計模式之代理模式

代理模式

GitHub代碼鏈接
代理模式(Proxy Pattern)中,一個類代表另一個類的功能。

什么是代理模式

代理模式為其他對象提供一種代理,以控制對這個對象的訪問。

解決了什么問題

代理模式解決了直接訪問對象時帶來的問題,比如直接訪問的對象在遠程機器上。

優(yōu)點

  • 職責(zé)清晰
  • 高擴展性
  • 智能化

缺點

  • 由于在客戶和真實主題之間增加了代理對象,因此有些類型的代理模式可能會造成請求速度變慢。
  • 實現(xiàn)代理模式需要額外的工作,有些代理模式實現(xiàn)較為復(fù)雜

代碼實現(xiàn)

1. 實現(xiàn)一個Image接口

//Image 接口
type Image interface {
    Display()
}

2. 實現(xiàn)一個RealImage類,作為被代理類

//RealImage 原本的image類
type RealImage struct {
    FileName string
}

//NewRealImage 實例化RealImage
func NewRealImage(filename string) *RealImage {
    return &RealImage{
        FileName: filename,
    }
}

//Display RealImage實現(xiàn)Image接口的Display方法
func (ri *RealImage) Display() {
    fmt.Printf("Displaying %s.\n", ri.FileName)
}

3. 實現(xiàn)一個代理類

//MyProxyImage 代理Image類
type MyProxyImage struct {
    Realimg  *RealImage
    FileName string
}

//NewMyProxyImage 實例化代理Image類
func NewMyProxyImage(filename string) *MyProxyImage {
    return &MyProxyImage{
        FileName: filename,
    }
}

//Display 實現(xiàn)Image接口函數(shù)
func (pi *MyProxyImage) Display() {
    if pi.Realimg == nil {
        pi.Realimg = NewRealImage(pi.FileName)
    }
    pi.Realimg.Display()
}

上一篇

12.Golang設(shè)計模式之享元模式

下一篇

14.Golang設(shè)計模式之責(zé)任鏈模式

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容