delegation and interface

i m reading Grand's Patterns in java, he says that delegation and interface patterns are often used together, however i wasnot able to find any references, i cant quite see why that is?
[201 byte] By [c03zw] at [2007-9-30 13:47:42]
# 1

GoF discusses delegation. They don't make it a pattern, rather they use it in several of their patterns. Their example of a Window delegating its area operation to a Rectangle and then being able to switch to using a Circle at runtime is dependent on Rectangle and Circle having the same "type", ie implementing the same interface. Here's a Java version of the delegation example on page 20 of "Design Patterns"

public class Window implements TwoD

{

TwoD my2D = new Rectangle(1,1);// we delegate area to this TwoD

// switch to circular delegate

void useCircle(double radius)

{my2D = new Circle(radius);}

// switch to rectangular delegate

void useRectangle(double width, double height)

{my2D = new Rectangle(width,height);}

// our area method uses the delegate

public double area()

{return my2D.area();}

public static void main(String[] args)

{

Window w = new Window();// construct a window

w.useRectangle(4.0, 6.0);// set the shape to a rectangle

System.out.println("area of rectangular window="+w.area());

w.useCircle(2.5);// set the shape to a circle

System.out.println("area of circular window="+w.area());

}

}

// 2 d shape used by Window, Circle and REctangle

interface TwoD

{

double area();// requires an area method

}

// rectangular shape

class Rectangle implements TwoD

{

double width, height;

Rectangle(double w, double h)

{

width = w;

height = h;

}

public double area(){return width*height;}

}

// circular shape

class Circle implements TwoD

{

double radius;

Circle(double r)

{

radius = r;

}

public double area(){return Math.PI*radius*radius;}

}

pkwooster at 2007-7-4 23:20:56 > top of Java-index,Other Topics,Patterns & OO Design...
# 2
many thanks for that! what is GoF? could you recommand some good resources of design patterns please?
c03zw at 2007-7-4 23:20:56 > top of Java-index,Other Topics,Patterns & OO Design...
# 3

GoF is the "Gang of Four". They are Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides. Their book [url=http://www.amazon.com/gp/reader/0201633612/ref=sib_dp_pt/002-3446478-7347205#reader-link]Design Patterns, Elements of Object-Oriented Software[/url] is the classic text on the topic, and is often just called the GoF book.

pkwooster at 2007-7-4 23:20:56 > top of Java-index,Other Topics,Patterns & OO Design...