Friday, December 13, 2013

Proxy Pattern

In Proxy pattern, a class represents functionality of another class. This type of design pattern comes under structural pattern.
In Proxy pattern, we create object having original object to interface its functionality to outer world.
Implementation
We're going to create a Person interface and concrete classes implementing the Person interface.ProxyPerson is a a proxy class to reduce memory footprint of RealPerson object loading.
ProxyPatternDemo, our demo class will use ProxyPerson to get a Person object to load and display  Name as it needs.



Step 1

Create an interface.
Person.java
public interface Person {
   void displayName();
}

Step 2

Create concrete classes implementing the same interface.
RealPerson.java
public class RealPerson implements Person {

   private int id;
   private String name;

   public RealPerson(int id){
      this.id = id;
      loadFromDb(id);
   }

   @Override
   public void displayName() {
      System.out.println("Person Name " + name);
   }

   private void loadFromDb(int id){
      System.out.println("Loading Person Details From DB");
//some logic to get name from db and set that name
//this.name = name;
   }
}

ProxyPerson.java
public class ProxyPerson implements Person{

   private RealPerson realPerson;
   private int id;
   private String name;

   public ProxyImage(int id){
      this.id = id;
   }

   @Override
   public void displayName() {
      if(realPerson == null){
         realPerson = new RealPerson(id);
      }
      realPerson.displayName();
   }
}

Step 3

Use the ProxyPerson to get object of RealPerson class when required.
ProxyPatternDemo.java
public class ProxyPatternDemo {
   public static void main(String[] args) {
      Person person = new ProxyPerson(1);

      //person name will fetch from db
      person.displayName(); 
      System.out.println("");
      //person will not fetch from db
      person.displayName(); 
   }
}

Step 4

Verify the output. For example in db  a person with name xyz  and  id 1.
Loading Person Details from DB
Person Name xyz


Person Name xyz

No comments:

Post a Comment

Distributed Transactions

What is a distributed transaction?  Transactions that span over multiple physical systems or computers over the network, are simply termed D...