Member-only story
Proxy Design pattern
The Proxy Design Pattern provides a proxy class that acts as an intermediary for controlling access to the real object. The proxy class implements the same interface as the real object and manages its creation and access.
Example:- Flow Diagram
protocol Image {
func display()
}
final class RealImage: Image {
private let path: String
init(path: String) {
self.path = path
// Simulate loading the image from the disk or network
print("Loading image from \(path)")
}
func display() {
print("Displaying image from \(path)")
}
}
final class ImageProxy: Image {
private let path: String
private var realImage: RealImage?
init(path: String) {
self.path = path
}
func display() {
if realImage == nil {
realImage = RealImage(path: path)
}
realImage?.display()
}
}
Use Case: Providing controlled access to an object, adding functionalities like lazy loading, caching, or security.
Real-life Scenario: Imagine a website using a caching mechanism to serve images. The user requests an image, but instead of immediately fetching it from the server, a proxy object might first check its local cache. If the image is already cached, it’s served from the cache, improving performance. If not, the proxy fetches the image from the server and stores it in the cache for future requests.
Here are some more real-time use cases where the Proxy Design Pattern can be applied in iOS development: