Proxy Design Pattern — 3 Minute Series

Interceptor. Actual instance protector.

Elric Edward
2 min readSep 23, 2022
Proxy Design Pattern is a fence to protect your actual instance.
Photo by Simon Maage on Unsplash

_00 / Concept

The proxy pattern provides a layer to handle client requests. So, instead of calling and responding by the actual instance, the proxy can intercept the request and help answer.

There are three types of proxies Virtual Proxy, Remote Proxy, and Protection Proxy. The basic concepts are similar, so being a wise user is essential. Using each type of proxy at the right time is our duty.

  • Virtual Proxy: a proxy to delay the creation process until you need it.
  • Remote Proxy: a proxy to handle cache response in your local.
  • Protection Proxy: a proxy to handle authentication.

_01 / Key Roles

Let’s take the Virtual Proxy as an example. When implementing Proxy Design Pattern, ensure your proxy implements the same interface as your actual instance.

interface FileManager { 
setTime: (time: number) => void
setName: (name: string) => void
read: () => void
}
class RealFileManager implements FileManager {
file: LoadedFile
constructor(path, loader) {
// trigger the resource monster here
this.file = loader(path)
}
setTime(time) {
this.file.time = time
}
setName(name) {
this.file.name = name
}
read() {
this.file.read()
}
}
class ProxyFileManager implements FileManager {
fileManager: FileManager
name: string
time: number
loader: (path) => File
constructor(path, loader) {
this.path = path
this.loader = loader
}
setTime(time) {
if(this.fileManager) {
this.fileManager.setTime(time)
} else {
this.time = time
}
}
setName(name) {
if(this.fileManager) {
this.fileManager.setName(name)
} else {
this.name = name
}
}
read() {
if(this.fileManager) {
this.fileManager.read()
} else {
// delay the resource monster triggering time
this.fileManager = new RealFileManager(this.path, this.loader)
if(this.name) this.fileManager.setName(name)
if(this.time) this.fileManager.setTime(time)
this.fileManager.read()
}
}
}

_02 / Trade-offs

🟢 Each type of proxy has its benefit, like delay in the creation time, cache response, and authentication protection.
🔴 Complexity, we pay an effort to add code. The interceptor is going to add a lot of logic.

--

--