DEV Community

Shirin Monzavi
Shirin Monzavi

Posted on

๐Ÿš€๐๐จ๐จ๐ฌ๐ญ ๐๐ž๐ซ๐Ÿ๐จ๐ซ๐ฆ๐š๐ง๐œ๐ž & ๐’๐ž๐œ๐ฎ๐ซ๐ข๐ญ๐ฒ ๐ฐ๐ข๐ญ๐ก ๐ญ๐ก๐ž ๐๐ซ๐จ๐ฑ๐ฒ ๐๐š๐ญ๐ญ๐ž๐ซ๐ง๐Ÿš€

โ‰๏ธ ๐Œ๐จ๐ญ๐ข๐ฏ๐š๐ญ๐ข๐จ๐ง
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)