Java Design Patterns Tutorial - Java Design Pattern - Proxy Pattern








In Proxy pattern, a class represents functionality of another class.

Proxy pattern is a structural pattern.

In Proxy pattern, we create object with original interface to expose its functionality to outer world.

Example

interface Printer {
   void print();//from   ww  w  .ja  v  a  2s.  com
}
class ConsolePrinter implements Printer {
   private String fileName;

   public ConsolePrinter(String fileName){
      this.fileName = fileName;
   }
   @Override
   public void print() {
      System.out.println("Displaying " + fileName);
   }
}
class ProxyPrinter implements Printer{
   private ConsolePrinter consolePrinter;
   private String fileName;

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

   @Override
   public void print() {
      if(consolePrinter == null){
         consolePrinter = new ConsolePrinter(fileName);
      }
      consolePrinter.print();
   }
}
public class Main {
  
   public static void main(String[] args) {
      Printer image = new ProxyPrinter("test");
      image.print();   
   }
}

The code above generates the following result.