Java Design Patterns Proxy Patterns

Introduction

Proxy Patterns provide a placeholder for another object to control access to it.

Proxy Patterns use a class as an interface to something else.

Use case

  • Network use proxy to route requests.

Example

abstract class Job {
   public abstract void doJob();
}

class RealJob extends Job {
   @Override//ww  w.  j  av  a 2 s. c om
   public void doJob() {
      System.out.println("concrete subject");
   }
}

class Proxy extends Job {
   RealJob realJob;

   @Override
   public void doJob() {
      System.out.println("Proxy call happening now");
      if (realJob == null) {
         realJob = new RealJob();
      }
      realJob.doJob();
   }
}

public class Main {
   public static void main(String[] args) {
      Proxy px = new Proxy();
      px.doJob();
   }
}



PreviousNext

Related