Design Patterns, Java, OOP, Programming, Proxy, structural design patterns

Design Patterns: Proxy

Hi guys, Today’s pattern is named Proxy and comes under the Structural family’s patterns.

This design pattern helps us to surrogate another object in order to change and control its behavior.

The definition of Proxy design pattern from the GoF book.

Provide a surrogate or placeholder for another object to control access to it.

The Proxy design pattern is very easy in use. We can use it in many ways, creating an expensive object on-demand, controlling access to the original object, and performing additional actions when an object is accessed.

Create an object on demand

Sometimes, we need to create an object only if it is necessary especially in the case that object is expensive. So, we don’t want to load it in memory until the first access.

Control access to an object

We can use it easily in order to control access to an object. For example, we want to provide full access to an object if the user is the Admin and a partially access when it is a simple user. Hold on, you will see an example using control access in a while.

Additional actions in object

Last but not least, we can use a proxy design pattern in order to add new actions to an object. For example, we can create a new instance of an object and lock this object behavior in order to be sure that no one can change its behavior.

Example

Let’s suppose that we have a system and there is a need to have users with privileges. The admin user is able to use all functionalities even delete, and a simple user has limited access to those functionalities.

We start creating an interface in order to define the commands.

Let’s implement those commands.

It is time to provide the right privileges to each user.

Create an example using the classes above.

Output:

You can download the source code from GitHub.