What is Proxy pattern
A proxy, in its most general form, is a class functioning as an interface to something else. A proxy is a wrapper or agent object that is being called by the client to access the real serving object behind the scenes.
When using this pattern
- The access to an object should be controlled
- Additional functionality should be provided when accessing an object.
Example in Go
package main
import (
"fmt"
)
type Car interface {
drive()
}
type Driver struct {
age int
}
type RealCar struct {
driver Driver
}
func (c RealCar) drive() {
fmt.Println("I am driving!")
}
type ProxyCar struct {
driver Driver
car RealCar
}
func (c ProxyCar) drive() {
if c.driver.age < 20 {
fmt.Println("Too young, cannot drive")
} else {
c.car.drive()
}
}
func main() {
driver := Driver{1}
car := ProxyCar{driver, RealCar{}}
car.drive()
driver = Driver{40}
car = ProxyCar{driver, RealCar{}}
car.drive()
}
Top comments (0)