Saturday, October 3, 2009

Patterns - 030: Structural patterns ( Counting Proxy )

The Counting Proxy pattern is useful in designing a set of additional operations such as logging and counting that need to be performed before and/or after a client object invokes a method on a service pr ovider object.

One of the characteristics of a well-designed object is that it offers focused functionality. In other words, an object, ideally, should not do various unr elated things.

Encapsulating the logging, counting and other similar functionality into a separate object leaves the service provider object with only the functionality that it is designed to offer.

A counting proxy is designed to have the same interface as the service provider object that a client accesses. Instead of accessing the service provider object directly, client objects invoke methods on the counting proxy. The proxy performs the required logging and counting and forwards the method call to the service provider object.


(counting_proxy_prototype)


Source for Order

public class Order implements OrderIF {
public Vector getAllOrders() {
FileUtil fileUtil = new FileUtil();
Vector v = fileUtil.fileToVector("orders.txt");
return v;
}
}


Source for OrderProxy


public class OrderProxy implements OrderIF {
private int counter = 0;
public Vector getAllOrders() {
Order order = new Order();
counter++;
long t1 = System.currentTimeMillis();
Vector v = order.getAllOrders();
long t2 = System.currentTimeMillis();
long timeDiff = t2 - t1;
String msg =
"Iteration=" + counter + "::Time=" + timeDiff +
"ms";
//log the message
FileUtil fileUtil = new FileUtil();
fileUtil.writeToFile("log.txt", msg, true, true);
return v;
}
}

No comments:

Post a Comment