โ๏ธ ๐๐จ๐ญ๐ข๐ฏ๐๐ญ๐ข๐จ๐ง
The Proxy pattern belongs to the structural category and provides a surrogate or placeholder for another object to control access to it. It is also known as a Surrogate.
๐ ๐๐๐๐ฅ-๐๐จ๐ซ๐ฅ๐ ๐๐๐๐ง๐๐ซ๐ข๐จ
Imagine we are building a document editor that embeds graphical objects in documents. Creating some graphical objects, like large raster images, is expensive. However, opening a document should be fast, so we want to avoid creating all expensive objects immediately.
These requirements suggest creating expensive objects on demand. So, what should we put in place of the image initially?
๐ฏ ๐บ๐๐๐๐๐๐๐ โ ๐ท๐๐๐๐ ๐ท๐๐๐๐๐๐
The solution is to use another object, an image proxy, that acts like the real image. The proxy behaves just like the image and takes care of instantiating it only when needed. The image proxy creates the real image only when the document editor requests it to display it. After creation, the proxy forwards all subsequent requests directly to the real image. Therefore, the proxy keeps a reference to the real image once itโs created.
๐ง ๐พ๐๐๐ ๐๐ ๐จ๐๐๐๐:
๐๐๐ฆ๐จ๐ญ๐ ๐ฉ๐ซ๐จ๐ฑ๐ฒ: When the real object is located elsewhere (over the network or on a different machine), communicating directly can be complex. A proxy can handle communication instead.
๐๐ข๐ซ๐ญ๐ฎ๐๐ฅ ๐ฉ๐ซ๐จ๐ฑ๐ฒ: When creating an object is expensive, a proxy can delay creation until itโs actually needed (lazy loading). See the real-world example above.
๐๐ซ๐จ๐ญ๐๐๐ญ๐ข๐จ๐ง ๐ฉ๐ซ๐จ๐ฑ๐ฒ: Controls access to the original object, enforcing access rights.
๐๐ฆ๐๐ซ๐ญ ๐ซ๐๐๐๐ซ๐๐ง๐๐: Replaces a simple reference but adds extra behavior each time the object is accessed (e.g., counting references).
๐ ๐๐๐ฅ๐๐ญ๐๐ ๐๐๐ญ๐ญ๐๐ซ๐ง๐ฌ:
๐๐๐๐ฉ๐ญ๐๐ซ: Provides a different interface for an object, while a proxy provides the same interface as its subject.
๐๐๐๐จ๐ซ๐๐ญ๐จ๐ซ: Similar in structure to a proxy but adds responsibilities to an object, whereas a proxy controls access.
๐ ๐ช๐๐
๐ ๐ฌ๐๐๐๐๐๐:
๐ ๐๐ข๐ญ๐๐ฎ๐ - https://github.com/shirin-monzavi/ProxyDesignPatternSample/tree/master
โ Have you ever used the Proxy Pattern in your projects? Share your experience!
Top comments (0)