Design Patterns — Proxy Pattern

Peter Lee
The Startup
Published in
2 min readJul 23, 2020

What is Proxy Pattern? When we should use it in our project? In this article, I will answer these questions and provides a simple example.

What is Proxy Pattern?

As far as I know, Design Pattern has three groups: Creational Design Patterns, Structural Design Patterns, and Behavioral Design Patterns. Applying Design Pattern helps your code easy to read, easy to understand, easy to maintain (add/modify features, and fix bugs). Design Pattern helps you make a good design system that guarantees your code complies with Software Design Principles. You can read my posts: Software Design Principles and SOLID Principles with a lot of examples for more details.

Proxy Pattern is a structural design pattern that lets you provide a substitute or placeholder for another object. A proxy controls access to the original object, allowing you to perform something either before and after the request gets through to the original object.

When we should use Proxy Pattern?

The answer is in the above definition: when you wanna control access to the original object and wanna hide the original object’s complexity (implementation) from the client.

Some real-world examples:

  • A bank’s credit card is a proxy for what is in our bank account. It can be used in place of cash and provides a means of accessing that cash when required. And that’s exactly what the Proxy pattern does: “Controls and manage access to the object they are protecting”.
  • A company or corporate has a proxy that restricts few site access. The proxy first checks the host you are connecting to, if it isn’t a part of a restricted site list, then it connects to the real internet.

Class Diagram and Sequence Diagram

Class Diagram and Sequence Diagram of Proxy Pattern. Source: wikipedia.org

A simple Example

Assume we wanna run some statements on the command line and need to check permission before do it. Apply the above class diagram, we will build our class diagram:

Class Diagram

Here is our code:

Finally, this is the main program:

Output:

*******************************
Command: ls -l executed!
Command: grep 'single' ~/Desktop/software_design_principles executed!
You have no permission executing the command rm -rf ~/Desktop

Summary

  • Proxy Pattern is the core design pattern of some frameworks. Example: Spring Framework. It is used in the fact widely.
  • Learning Design Patterns isn’t difficult, you can found a lot of materials on the internet but identify and apply it that is very difficult.
  • Hope this article will give you some useful. If you have some doubt/questions please comment here. Thank you for your reading.

References

--

--