Design Patterns Tutorial
A tutorial on GOF design patterns. This tutorial is for beginners who are going to learn design patterns for the first time. Each pattern is expalined with suitable examples.
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.

Categories: Structural Patterns. No Comments on Proxy Pattern in Design Patterns a Java Example

Proxy pattern is used to provide a surrogate or placeholder for another object to control access to it. Let’s learn in detail about this design pattern.

 

Proxy Pattern’s Intent

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

 

Also Known As

Surrogate

 

Proxy Pattern’s Motivation

Sometimes we need the ability to control the access to an object. For example if we need to use only a few methods of some costly objects we’ll initialize those objects when we need them entirely. Until that point we can use some light objects exposing the same interface as the heavy objects.

 

These light objects are called proxies and they will instantiate those heavy objects when they are really need and by then we’ll use some light objects instead.

 

This ability to control the access to an object can be required for a variety of reasons: controlling when a costly object needs to be instantiated and initialized, giving different access rights to an object, as well as providing a sophisticated means of accessing and referencing objects running in other processes, on other machines.

 

Consider for example an image viewer program. An image viewer program must be able to list and display high resolution photo objects that are in a folder, but how often do someone open a folder and view all the images inside.

 

Sometimes you will be looking for a particular photo, sometimes you will only want to see an image name. The image viewer must be able to list all photo objects, but the photo objects must not be loaded into memory until they are required to be rendered.

 

Proxy Pattern’s Applicability

Proxy pattern is applicable when:

  1. A remote proxy provides a local representative for an object in a different address space.

 

  1. A virtual proxy creates expensive objects on demand.

 

  1. A protection proxy controls access to the original object. Protection proxies are useful when objects should have different access rights.

 

  1. A smart reference is a replacement for a bare pointer that performs additional actions when an object is accessed.

 

Proxy Pattern’s Structure

The structure of proxy pattern is as shown below:

Proxy Pattern Structure

 

Participants

The participants in proxy pattern are:

  • Proxy: Maintains a reference that lets the proxy access the real subject. Provides an interface identical to Subject so that the Proxy can be substituted for the real subject. Controls access to the real subject.
  • Subject: Defines the common interface for RealSubject and Proxy so that a Proxy can be used anywhere a RealSubject is expected.
  • RealSubject: Defines the real object that the proxy represents.

 

Collaborations

Proxy forwards requests to RealSubject when appropriate, depending on the kind of proxy.

 

Proxy Pattern’s Consequences

The Proxy pattern introduces a level of indirection when accessing an object. The additional indirection has many uses, depending on the kind of proxy:

  1. A remote proxy can hide the fact that an object resides in a different address space.
  2. A virtual proxy can perform optimizations such as creating an object on demand.
  3. Both protection proxies and smart references allow additional housekeeping tasks when an object is accessed.

 

Proxy Pattern’s Implementation

The Proxy pattern can exploit the following language features:

  1. Overloading the member access operator in C++: C++ supports overloading operator->, the member access operator. Overloading this operator lets you perform additional work whenever an object is dereferenced.

 

  1. Using doesNotUnderstand in Smalltalk: Smalltalk provides a hook that you can use to support automatic forwarding of requests. Smalltalk calls doesNotUnderstand: aMessage when a client sends a message to a receiver that has no corresponding method. The Proxy class can redefine doesNotUnderstand so that the message is forwarded to its subject.

 

  1. Proxy doesn’t always have to know the type of real subject: If a Proxy class can deal with its subject solely through an abstract interface, then there’s no need to make a Proxy class for each RealSubject class; the proxy can deal with all RealSubject classes uniformly. But if Proxies are going to instantiate RealSubjects (such as in a virtual proxy), then they have to know the concrete class.

 

Sample Code (Java Example)

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.

 

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

//CommandExecutor.java
public interface CommandExecutor {
 
    public void runCommand(String cmd) throws Exception;
}

//CommandExecutorImpl.java
import java.io.IOException;
 
public class CommandExecutorImpl implements CommandExecutor {
 
    @Override
    public void runCommand(String cmd) throws IOException {
                //some heavy implementation
        Runtime.getRuntime().exec(cmd);
        System.out.println("'" + cmd + "' command executed.");
    }
 
}

 

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
public class CommandExecutorProxy implements CommandExecutor {
 
    private boolean isAdmin;
    private CommandExecutor executor;
     
    public CommandExecutorProxy(String user, String pwd){
        if("Pankaj".equals(user) && "J@urnalD$v".equals(pwd)) isAdmin=true;
        executor = new CommandExecutorImpl();
    }
     
    @Override
    public void runCommand(String cmd) throws Exception {
        if(isAdmin){
            executor.runCommand(cmd);
        }else{
            if(cmd.trim().startsWith("rm")){
throw new Exception("rm command is not allowed for non-admin users.");
            }else{
                executor.runCommand(cmd);
            }
        }
    }
 
}

 

Here is the client program::

//ProxyPatternTest.java
public class ProxyPatternTest {
 
    public static void main(String[] args){
        CommandExecutor executor = new CommandExecutorProxy("Pankaj", "wrong_pwd");
        try {
            executor.runCommand("ls -ltr");
            executor.runCommand(" rm -rf abc.pdf");
        } catch (Exception e) {
            System.out.println("Exception Message::"+e.getMessage());
        }
         
    }
 
}

 

Proxy Pattern’s Known Uses

Following are the examples in Java API where proxy pattern is used:

  • lang.reflect.Proxy
  • rmi.*, the whole API actually.

 

Related Patterns

An adapter provides a different interface to the object it adapts. In contrast, a proxy provides the same interface as its subject. However, a proxy used for access protection might refuse to perform an operation that the subject will perform, so its interface may be effectively a subset of the subject’s.

 

Although decorators can have similar implementations as proxies, decorators have a different purpose. A decorator adds one or more responsibilities to an object, whereas a proxy controls access to an object.

 

Non-Software Example

The Proxy provides a surrogate or place holder to provide access to an object. A check or bank draft is a proxy for funds in an account. A check can be used in place of cash for making purchases and ultimately controls access to cash in the issuer’s account.

 

Proxy Pattern Real World Example

 

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Suryateja Pericherla

Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.

He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.

He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.

Note: Do you have a question on this article or have a suggestion to make this article better? You can ask or suggest us by filling in the below form. After commenting, your comment will be held for moderation and will be published in 24-48 hrs.

Leave a Reply

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

Drag To Verify