What is Proxy Design Pattern?

Provide a surrogate or placeholder for another object. This Place holder object provides some advantages, few are as below.

#1. to Access Remote Object.
#2. to control access of few methods of original object.
#3. it may be costly(consumes more memory or time) to use original object.
…and many more.

Below is an example, of using place holder object of VideoProxy instead of original Video object.

As shown in example below, object of Video class loads video file, even to display thumb nail. As known it consumes more memory to load multiple video thumb nails, in a single screen.

To keep memory consumption minimal, ProxyVideo has been implemented, which displays an Image to display thumb nail. And the video file is loaded, only when user want to play the video, that too only the specific video file which the user opted to view, will be loaded to play.

public interface IVideo {
   void displayThumbnail();
   void playVideo();
}

public class Video implements Image {

   private String fileName;

   public Video(String fileName){
      this.fileName = fileName;
   }

   @Override
   public void displayThumbnail() {
      loadVideoFromStorage();
      System.out.println("Displaying Thumbnail of " + fileName);
   }

   private void loadVideoFromStorage(){
      System.out.println("Loading actual video... " + fileName);
   }

   @override
   public void playVideo()
   {
      loadVideoFromStorage();
   }
}

public class ProxyVideo implements IVideo{

   private Video objVideo;
   private String fileName;

   public Video(String fileName){
      this.fileName = fileName;
   }

   @Override
   public void displayThumbnail() {
      String thumbnail_name = fileName+"_thumbnail.jpg";
      System.out.println("Display Thumbnail Image..."+thumbnail_name);
   }

   @Override
   public void playVideo() {
      objVideo = new Video(fileName);
      objVideo.playVideo();
   }
}

In this example, Aggregation is used(Read more on Composition and Aggregation), instead inheritance can be used here.

Difference between Proxy and Adapter Pattern

Adapter Pattern is to change the interface of class A to the expectations of another class B. The typical implementation is a wrapper class or set of classes.

Proxy Pattern is similar, but the purpose is different. The purpose of the proxy pattern is to create a stand-in for a real resource. As already briefed, this stand-in is required as the actual object is remotely located or it is expensive to create actual object or you want to give controlled access to methods of actual class, etc…

You may also like to read:
What is Factory Design Pattern
How to implement Singleton Design Pattern
Can Adapter Pattern use Composition
Adapter Pattern using Inheritance