I have a query regarding the Delegation Design Principle in OOP. I will use the Window & Rectangle classes example from the GOF design patterns book to explain my query.
public class Window
{
Rectangle myDelegate;
public void Area()
{
return myDelegate.Area();
}
}
public class Rectangle
{
public int Area()
{
return 2*3;
}
}
My question is: Can the Rectangle( the delegate) have a reference to the window( the parent class). i.e:
public class Window
{
Rectangle myDelegate;
public int myArea;
public void Area()
{
myDelegate.Area();
}
}
public class Rectangle
{
Window myParent;
public void Area()
{
myParent.myArea = 2 * 3;
}
}
In non trivial cases the above would make it much more convenient for the delegate to update the state of the parent.
Is that logical or am I missing something here?
Thanks!
public interface IShape { void Area(); void SetArea(int area); } public class Window : IShape { private IShape rectangle; private int myArea; public Window(IShape shape) { rectangle = shape; } public void SetArea(int area) { myArea = area; } public void Area() { rectangle.Area(); } } public class Rectangle : IShape { private IShape window; public Rectangle(IShape shape) { window = shape; } public void Area() { SetArea(2 * 3); } public void SetArea(int area) { window.SetArea(area); } }