代理模式
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()
}