DEV Community

Difan Chen
Difan Chen

Posted on

[Design Pattern in Go] Proxy

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 (

type Car interface {

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 {

func main() {
    driver := Driver{1}
    car := ProxyCar{driver, RealCar{}}

    driver = Driver{40}
        car = ProxyCar{driver, RealCar{}}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)