Java Structural Design Patterns – Proxy Pattern

Do you remember signing your class attendance sheet on behalf of your friend (well of course your teacher doesn’t have to know :)). That is called Proxy. It means “in place of” or “on behalf”.  The Proxy Pattern comes under Structural Design Pattern. Proxy pattern is very simple to understand; in this pattern mainly 2 classes are used real class and proxy class. A proxy class is used to access real class object. A proxy class which acts as a intermediary for requests coming from client and provides the control for accessing the target (real) object. We can say that proxy class provides the security to the original object from the outside world. Proxy pattern is also called as Surrogate or Placeholder.

In your application if you observe below points then you can use Proxy Pattern.

  • Need to control object access.
  • You are required to do some additional processing before object is accessed.

Proxy Pattern by Example

For simple understanding we will take a day to day life example, where you try to access a particular website and once you access you get a message that, the site is banned by your organization network. We will try to simulate something like that.

Lets define a small interface Network

Later we will define two concrete implementation of this interface. One will be RealNetwork, which is core implementation and other will be its Proxy.

You can see that, the Real implementation do not have any restrictions of any sort. Lets see proxy.

Now, as its Proxy, it has to do some checks before allowing the connection. It does that by checking the requested url in predefined site list and then decides on connection.

Running the example

Here is our demo client-

Output

Drawback

With this pattern we are introducing another layer of abstraction which may be an issue if the Real interface is being used by some clients (as shown in above output). This will cause disparate behaviour as same functionality is being access using different means.

Conclusion

In proxy pattern even if the client would use the proxy object it is similar to using like a real object, because both the classes implement the same interface. So in Proxy pattern it provides controlled access to objects and object will get created with original interface to represents its functionality to outer world.

Add a Comment

Your email address will not be published. Required fields are marked *