September 14, 2001
Q: What are delegates?
A: When an object receives a request, the object can either handle the request itself or pass the request on to a second object to do the work. If the object decides to pass the request on, you say that the object has forwarded responsibility for handling the request to the second object.
The following Stack
class provides a simple example of composition and forwarding:
public class Stack { private java.util.ArrayList list; public Stack() { list = new java.util.ArrayList(); } public boolean empty() { return list.isEmpty(); } public Object peek() { if( !empty() ) { return list.get( 0 ); } return null; } public Object pop() { if( !empty() ) { return list.remove( 0 ); } return null; } public Object push( Object item ) { list.add( 0, item ); return item; } }
Through composition, Stack
holds on to an ArrayList
instance. As you can see, Stack
then forwards the requests to the ArrayList
instance. Simple composition and request forwarding (such as that of the Stack
class presented above) is often mistakenly referred to as delegation.
True delegation is a bit more rigorous. In true delegation, the object that forwards the request also passes itself as an argument to the delegate object, which actually does the work.
Think of true delegation this way: Something sends a request to object1
. object1
then forwards the request and itself to object2
-- the delegate. object2
processes the request and does some work.
For an excellent example of true delegation, please see the example code for the State pattern in Design Patterns Elements of Reusable Object-Oriented Software by Erich Gamma, et al (see Resources). You can also check out "How to Implement State-Dependent Behavior" by Eric Armstrong (JavaWorld, August 1997).
Learn more about this topic
- The famous Gang of Four bookDesign Patterns, Eric Gamma, Richard Helm, Ralph Johnson, John Vlissides (Addison-Wesley Publishing Co., 1995; ISBN0201633612)
http://www.amazon.com/exec/obidos/ASIN/0201633612/javaworld - "How To Implement State-Dependent Behavior," Eric Armstrong (JavaWorld, August 1997)
http://www.javaworld.com/javaworld/jw-08-1997/jw-08-stated.html - Want more? See the Java Q&A Index for the full Q&A catalog
http://www.javaworld.com/columns/jw-qna-index.shtml - For over 100 insightful Java tips from some of the best minds in the business, visit JavaWorld's Java Tips Index
http://www.javaworld.com/columns/jw-tips-index.shtml - Sign up for JavaWorld's free weekly email newsletters
http://www.idg.net/jw-subscribe - You'll find a wealth of IT-related articles from our sister publications at IDG.net
This story, "Delegates" was originally published by JavaWorld.