rhk98
rhk98

Reputation: 117

Delegation Pattern( or OO Design Principle) question

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

Answers (3)

mikemanne
mikemanne

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:

  • It allows the same delegate to be shared among multiple parents. This could be useful if the delegate represents a finite resource ("port 1234") or if the delegate is expensive to instantiate.
  • The parent can control whether or not they care about the delegate's behavior. Don't care? Don't register interest in the event.
  • Fewer maintenance considerations (as Boris pointed out above)

Upvotes: 0

zbugs
zbugs

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

Boris Pavlović
Boris Pavlović

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

Related Questions