Design patterns

The proxy pattern

The proxy pattern defines a proxy class for the original class without changing the interface of the original class. The main purpose is to control access, not enhance functionality. This is the biggest difference from the decorator pattern. In general, we make the proxy class implement the same interface as the original class, but if the original class does not define the interface and the original class code is not developed and maintained by us, in this case, we make the proxy class inherit the methods of the original class to implement the proxy.

In short, there are two ways to implement a proxy:

  • The proxy class implements the same interface as the original class
  • The proxy class inherits from the original class

Application scenarios

The proxy mode is used to develop non-functional requirements for business systems, such as monitoring, logging, statistics, authentication, traffic limiting, transactions, idempotent verification, etc. The proxy pattern can be used in RPC and caching scenarios in addition to decoupling additional and business functions into proxy classes, where programmers only need to focus on the business itself.

code

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 Instantiate real objects, etc. Res += "pre:" res += p.real.do () res += p.real.do () res += p.real.do () res += ":after" return res }Copy the code

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() } }Copy the code

The results

=== RUN TestProxy -- PASS: TestProxy (0.00s) PASS Process finished with exit code 0Copy the code

The resources

  • Github.com/senghoo/gol…