Proxy Pattern
Author: Deron Eriksson
Description: This Java tutorial describes the proxy pattern, a structural design pattern.
Tutorial created using: Windows Vista || JDK 1.6.0_11 || Eclipse JEE Ganymede SR1 (Eclipse 3.4.1)


Page:    1 2 >

The proxy pattern is a structural design pattern. In the proxy pattern, a proxy class is used to control access to another class. The reasons for this control can vary. As one example, a proxy may avoid instantiation of an object until the object is needed. This can be useful if the object requires a lot of time or resources to create. Another reason to use a proxy is to control access rights to an object. A client request may require certain credentials in order to access the object.

Now, we'll look at an example of the proxy pattern. First, we'll create an abstract class called Thing with a basic sayHello() message that includes the date/time that the message is displayed.

Thing.java

package com.cakes;

import java.util.Date;

public abstract class Thing {

	public void sayHello() {
		System.out.println(this.getClass().getSimpleName() + " says howdy at " + new Date());
	}

}

FastThing subclasses Thing.

FastThing.java

package com.cakes;

public class FastThing extends Thing {

	public FastThing() {
	}

}

SlowThing also subclasses Thing. However, its constructor takes 5 seconds to execute.

SlowThing.java

package com.cakes;

public class SlowThing extends Thing {

	public SlowThing() {
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}

The Proxy class is a proxy to a SlowThing object. Since a SlowThing object takes 5 seconds to create, we'll use a proxy to a SlowThing so that a SlowThing object is only created on demand. This occurs when the proxy's sayHello() method is executed. It instantiates a SlowThing object if it doesn't already exist and then calls sayHello() on the SlowThing object.

Proxy.java

package com.cakes;

import java.util.Date;

public class Proxy {

	SlowThing slowThing;

	public Proxy() {
		System.out.println("Creating proxy at " + new Date());
	}

	public void sayHello() {
		if (slowThing == null) {
			slowThing = new SlowThing();
		}
		slowThing.sayHello();
	}

}

(Continued on page 2)

Page:    1 2 >


Related Tutorials: