代理模式
发布者:admin 发表于:446天前 阅读数:732 评论:0

代理模式用于延迟处理操作或者在进行实际操作前后进行其它处理。

[]()代理模式的常见用法有 虚代理

COW代理

远程代理

保护代理

Cache 代理

防火墙代理

同步代理

智能指引

等。。。

proxy.go

package proxy

type Subject interface {
    Do() string
}

type RealSubject struct{}

func (RealSubject) Do() string {
    return "real"
}

type Proxy struct {
    real RealSubject
}

func (p Proxy) Do() string {
    var res string

    // 在调用真实对象之前的工作,检查缓存,判断权限,实例化真实对象等。。
    res += "pre:"

    // 调用真实对象
    res += p.real.Do()

    // 调用之后的操作,如缓存结果,对结果进行处理等。。
    res += ":after"

    return res
}

proxy_test.go

package proxy

import "testing"

func TestProxy(t *testing.T) {
    var sub Subject
    sub = &Proxy{}

    res := sub.Do()

    if res != "pre:real:after" {
        t.Fail()
    }
}