EMZETT.
Login

Proxy pattern

In short: A proxy is a stand-in object with the same interface as the real object that sits in front of it. It can check, delay, cache or log access.

Types

  • Virtual proxy (lazy loading): the expensive object (large image, database connection) is created only when really needed (Lazy Evaluation).
  • Protection proxy: checks beforehand whether the caller is allowed.
  • Cache proxy: remembers results (caching strategies, Memoization).
  • Remote proxy: acts as if the object were local but talks over the network (RPC, see GraphQL and gRPC).
  • Logging proxy: records calls.

Example

class Image:
    def show(self): ...
 
class RealImage(Image):
    def __init__(self, file):
        self.data = load(file)          # expensive
    def show(self): draw(self.data)
 
class ImageProxy(Image):
    def __init__(self, file):
        self.file, self.real = file, None
    def show(self):
        if self.real is None:           # load only the first time
            self.real = RealImage(self.file)
        self.real.show()

Distinction

Like the decorator and the Adapter the proxy wraps an object, but with a different goal: the proxy controls access with the same interface, the decorator adds functions, the adapter adapts a different interface. Do not confuse it with the network proxy (Proxy), which works on the same idea.

See also: Facade pattern