34

13.Golang设计模式之代理模式

 3 years ago
source link: https://studygolang.com/articles/30994
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

代理模式

GitHub代码链接 代理模式(Proxy Pattern)中,一个类代表另一个类的功能。

什么是代理模式

代理模式为其他对象提供一种代理,以控制对这个对象的访问。

解决了什么问题

代理模式解决了直接访问对象时带来的问题,比如直接访问的对象在远程机器上。

优点

  • 职责清晰
  • 高扩展性
  • 智能化

缺点

  • 由于在客户和真实主题之间增加了代理对象,因此有些类型的代理模式可能会造成请求速度变慢。
  • 实现代理模式需要额外的工作,有些代理模式实现较为复杂

代码实现

1. 实现一个Image接口

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

2. 实现一个RealImage类,作为被代理类

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

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

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

3. 实现一个代理类

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

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

//Display 实现Image接口函数
func (pi *MyProxyImage) Display() {
    if pi.Realimg == nil {
        pi.Realimg = NewRealImage(pi.FileName)
    }
    pi.Realimg.Display()
}

上一篇

12.Golang设计模式之享元模式

有疑问加站长微信联系

iiUfA3j.png!mobile

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK