Monday, May 28, 2012

Structural Patterns - 7.Proxy Pattern

Proxy pattern filters and customizes the data you want from the main big subject. Assume, we have a subject with nearly 200 properties into it. But frequently we may need 10 or 20 of them.

So, we will end-up in creating a proxy for the subject by filtering the 10 or 20 properties alone from the main subject.

Whenever we need those properties we may access the proxy instead of the main subject.

This will help us to get way from creating costly objects and business calls.

For example, Student will be our subject which contains data like attendance, marks, age,etc. But we may not interest in all the data except the attendance information. Instead of using the entire Student object, we will create a Proxy to the Student which provides the attendance details alone.

Proxy can add more functionalties before or after getting the attendance details from the Student Object.

Following diagram explains this pattern a bit more,


We can use the proxy object whenever we need to process the attendance for the student.
This proxy will internally communicate with the Student object with a singleton pattern.

Proxy Code snippet in Client:

  Student abc=new ProxyStudent();
  Student def=new ProxyStudent(); //Create Proxies for Student


In the Proxy Class,

public String getAttendance() {
  if(realStudent==null){  //Ensure singleton object for the Subject
   realStudent=new RealStudent();
  }
  return realStudent.getAttendance();
 }


 

No comments:

Post a Comment