The Proxy pattern is a structural design pattern that provides a placeholder or surrogate for another object to control access to it.
It acts as an interface to something else, whether it's a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate.
Key Components:
-
Subject: Defines the common interface for Real Subject and Proxy so that a Proxy can be used anywhere a Real Subject is expected.
-
Real Subject: The actual object that the proxy represents and controls access to.
-
Proxy: Maintains a reference to the Real Subject and controls access to it. May create or delete the Real Subject.
-
Client: Works with objects through the Subject interface, unaware of whether it's using a Proxy or Real Subject.
Benefits:
-
Access Control: Can control access to the real object, providing security or permission checks.
-
Lazy Initialization: Can defer the creation of expensive objects until they are actually needed.
-
Performance Optimization: Can cache results or add additional functionality without modifying the original object.
Types of Proxies:
-
Virtual Proxy: Controls access to expensive-to-create objects by creating them only when needed (lazy initialization).
-
Protection Proxy: Controls access to objects based on access rights or permissions.
-
Remote Proxy: Provides a local representative for an object in a different address space (e.g., network services).
-
Caching Proxy: Stores results of expensive operations and returns cached results when appropriate.