Golang Proxy Pattern

In this post, we will learn how to use and implement the Proxy Pattern in Golang with an example.

Proxy is a structural design pattern that lets you provide a substitute or placeholder for another object. A proxy controls access to the original object, allowing you to perform something either before or after the request gets through to the original object.

Proxy Pattern Class Diagram

The below diagram shows the generic structure of the Proxy Pattern:

The proxy pattern comprises the subject interface, the RealSubject class, and the Proxy class:
  • Subject is an interface for the RealObject and Proxy class.
  • The RealSubject object is created and maintained as a reference in the Proxy class. RealSubject is resource-sensitive, required to be protected, and expensive to create. RealObject is a class that implements the IRealObject interface. It has a performAction() method.
  • VirtualProxy is used to access RealObject and invoke the performAction() method

Golang Proxy Pattern Implementation

Let's refer to the above structure to create an example to demonstrates the usage of the Proxy.
Let's create a file named "proxy.go" and add the following source code to it:

package main

// importing fmt package
import (
	"fmt"
)

//IRealObject interface
type IRealObject interface {
	performAction()
}

//RealObject struct
type RealObject struct{}

//RealObject class method performAction
func (realObject *RealObject) performAction() {
	fmt.Println("RealObject performAction()")
}

//VirtualProxy struct
type VirtualProxy struct {
	realObject *RealObject
}

//VirtualProxy class method performAction
func (virtualProxy *VirtualProxy) performAction() {
	if virtualProxy.realObject == nil {
		virtualProxy.realObject = &RealObject{}
	}
	fmt.Println("Virtual Proxy performAction()")
	virtualProxy.realObject.performAction()
}

// main method
func main() {
	var object VirtualProxy = VirtualProxy{}
	object.performAction()
}

Output:

G:\GoLang\examples>go run proxy.go
Virtual Proxy performAction()
RealObject performAction()

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course

Comments