mirror of
https://github.com/tmrts/go-patterns.git
synced 2025-04-09 20:11:01 +00:00
1.4 KiB
1.4 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:
// To use proxy and to object they must implement same methods
type IObject interface {
ObjDo(action string)
}
// Object represents real objects which proxy will delegate data
type Object struct {
action string
}
// ObjDo implements IObject interface and handels all logic
func (obj *Object) ObjDo(action string) {
// Action behaiver
fmt.Printf("I can, %s", action)
}
// ProxyObject represents proxy object with intercepts actions
type ProxyObject struct {
object *Object
}
// ObjDo are implemented IObject and intercept action before send in real Object
func (p *ProxyObject) ObjDo(action string) {
if p.object == nil {
p.object = new(Object)
}
if action == "Run" {
p.object.ObjDo(action) // Prints: I can, Run
}
}
Usage
For more complex usage, see proxy/main.go or view in the Playground.