Proxy Design Pattern in Go

1. Definition

The Proxy Design Pattern provides a surrogate or placeholder for another object to control access to it. It can be used to add functionalities such as lazy initialization, logging, access control, or even computation offloading to remote services.

2. Problem Statement

Imagine you have an object that is resource-intensive to create or has operations that require certain access controls. Direct access to such objects might not be efficient or secure.

3. Solution

Use a separate proxy object that acts as an intermediary between the client and the real object. This proxy can handle additional operations like lazy initialization or access checks before delegating the request to the original object.

4. Real-World Use Cases

1. Lazy loading of large-sized images in a graphic editor.

2. Access control for file operations.

3. Remote proxies that communicate with objects in different processes or even on different machines.

5. Implementation Steps

1. Create an interface that both the real object and the proxy implement.

2. Define the proxy object to hold a reference to the real object.

3. Implement methods in the proxy that add the desired functionality and then delegate to the real object.

6. Implementation in Go

// Subject Interface
type Subject interface {
	Request() string
}
// RealSubject
type RealSubject struct{}
func (r *RealSubject) Request() string {
	return "RealSubject: Handling request."
}
// Proxy
type Proxy struct {
	realSubject *RealSubject
}
func (p *Proxy) Request() string {
	if p.realSubject == nil {
		p.realSubject = &RealSubject{}
	}
	// Here you can add extra functionality like logging, access control, etc.
	return "Proxy: Delegating to RealSubject -> " + p.realSubject.Request()
}
// Client code
func main() {
	proxy := &Proxy{}
	fmt.Println(proxy.Request())
}

Output:

Proxy: Delegating to RealSubject -> RealSubject: Handling request.

Explanation:

1. Subject is the common interface implemented by both RealSubject and Proxy.

2. RealSubject is the original object that does the actual operations.

3. Proxy contains a reference to RealSubject. When its methods are called, it can perform additional operations and then delegate to the real subject.

4. In the client code, instead of accessing RealSubject directly, we interact with the Proxy which controls the access to the RealSubject.

7. When to use?

Use the Proxy Design Pattern when:

1. You need to control the access to an object, either to shield some of its details or to add additional behavior.

2. You want to delay the instantiation and initialization of a heavy object until it's actually needed.

3. You want to implement shared access or caching for expensive network operations.


Comments