Structural type: IV proxy pattern

Time:2022-6-9

What is the proxy mode

Proxy mode is a structural design mode, which allows you to provide a substitute for the real service object to the client. The proxy receives the client’s request and performs some processing (access control, caching, etc.), and then passes the request to the service object.

Why proxy mode

In some cases, the client class does not want or cannot access the target object. In this case, the proxy class can be used to access.

How to implement proxy mode

package proxy

//Proxy mode

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

    //Work before calling real objects, check cache, judge permissions, instantiate real objects, etc..
    res += "pre:"

    //Call real object
    res += p.real.Do()

    //Operations after calling, such as caching results, processing results, etc..
    res += ":after"

    return res
}

advantage

  1. The proxy pattern acts as a mediator and protector between the client and the target object.
  2. Proxy mode extends the functionality of the target object.
  3. The proxy pattern classifies the target object and the client, which reduces the coupling of the system to a certain extent. The scalability of the program is increased.

shortcoming

  1. Agent mode will cause the increase of system classes and increase the complexity of the system.