1
0
Fork 0
mirror of https://github.com/tmrts/go-patterns.git synced 2025-04-09 20:11:01 +00:00
go-patterns/structural/proxy.md
2017-06-15 18:52:21 +03:00

1.1 KiB

Proxy Pattern

The proxy pattern provides an object that controls access to another object, intercepting all calls.

Implementation

The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate.

Short idea of implementation:

    type IObject interface {
        ObjDo(action string)
    }

    type Object struct {
        action string
    }

    func (obj *Object) ObjDo(action string) {
        // Action handler
        fmt.Printf("I do, %s", action)
    }

    type ProxyObject struct {
        object *Object
    }

    func (p *ProxyObject) ObjDo(action string) {
        if p.object == nil {
            p.object = new(Object)
        }
        if action == "Run" {
            p.object.ObjDo(action)
        }
    }

    func main() {
        newObj := new(ProxyObject)
        newObj.ObjDo("Run") // Prints: I can, Run
    }

Usage

For usage, see observer/main.go or view in the Playground.