Proxy Design Pattern With Examples

Proxy Design pattern is one of the Structural design pattern and in my opinion one of the simplest pattern to understand.

Proxy Design Pattern

Proxy design pattern intent according to GoF is:

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

The definition itself is very clear and proxy design pattern is used when we want to provide controlled access of a functionality.

Let’s say we have a class that can run some command on the system. Now if we are using it, its fine but if we want to give this program to a client application, it can have severe issues because client program can issue command to delete some system files or change some settings that you don’t want.

Here a proxy class can be created to provide controlled access of the program.

Proxy Design Pattern – Main Class

Since we code Java in terms of interfaces, here is our interface and its implementation class.

CommandExecutor.java

CommandExecutorImpl.java

Proxy Design Pattern – Proxy Class

Now we want to provide only admin users to have full access of above class, if the user is not admin then only limited commands will be allowed. Here is our very simple proxy class implementation.

CommandExecutorProxy.java

Proxy Design Pattern Client Program

ProxyPatternTest.java

Output of above proxy design pattern example program is:

Proxy design pattern common uses are to control access or to provide a wrapper implementation for better performance.

Java RMI package uses proxy pattern. That’s all for proxy design pattern in java.

By admin

Leave a Reply