Reputation: 117
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!
Upvotes: 1
Views: 251
Reputation: 3575
If those were my classes, and I needed the delegate to communicate back to the parent, I would create an event on the delegate and set the parent up as a listener. That has several benefits:
Upvotes: 0
Reputation: 601
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); } }
Upvotes: 0
Reputation: 64632
It's much easier to maintain unidirectional references. In this case it would be appropriate for the Window
to ask the rectangle of its own dimensions and use it to allocate the needed space. Then the Rectangle
would have a freedom to render itself in its space as it wants.
Upvotes: 1