Wednesday, June 1, 2016

Proxy Design Pattern in java tutorial

What is Proxy Design Pattern?

First of all its a structural pattern and Proxy means in place of.In our collage times we gave proxy in place of or on behalf of are literal meanings of proxy.There are many different flavors of proxy depending on its purpose.we may have a protection proxy to control access rights to an object.

For Example:

Let say you want to attach  an image with an e-mail .now suppose this email has to be sent to millions of consumers in an e-mail campaign.Attaching the image and sending along with the e-mail will be very heavy operation.

So what we can do instead send the image as a link to one of the servlet. The Place Holder of the image will be sent.Once the email reaches the consumer the image place holder will call the servlet and load the image at run time from server.

Now when to use Proxy Pattern:

It is used when we need to represent a complex object with a simpler one.If creation of object is expensive,its creation can be suspended till the necessity arises  and till then a simple object can represent it.The Simple Object is called the Proxy for the complex Object.

Implementation:

/**
 * @author Abhinaw.Tripathi
 *
 */

interface Image
{
 public void showImage();
}

class RealImage implements Image
{
public RealImage(URL url)
{
loadImage(url);
}
private void loadImage(URL url)
{
// operation to load image
}
@Override
public void showImage()
{
// TODO Auto-generated method stub
//display the image

}
}

class ProxyImage implements Image
{

private URL url;
public ProxyImage(URL url) {
this.url=url;
}


public ProxyImage(String string) {
// TODO Auto-generated constructor stub
}


@Override
public void showImage() {
// TODO Auto-generated method stub
RealImage real=new RealImage(url);
real.showImage();
}
 
}

public class ProxyPatternTest {

/**
*
*/
public ProxyPatternTest() {
// TODO Auto-generated constructor stub
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

     Image img1=new ProxyImage("testfolder/image1.png");
     Image img2=new ProxyImage("testfolder/image2.png");
     img1.showImage();  // you can do something like this.
}

}

No comments: