Design patterns in real world use case scenarios – Composite

Design patterns are set of best practices solutions to common problems. They are also an excellent dictionary which can enhance and speed up the communication between various team member. But they are also sometimes misused and lead to over-architected solutions.

By my opinion, every pattern usage in an application has to answer one simple questions:”What exact pain this pattern solves? ”

If that question doesn’t have a clear answer, I would challenge right there the decision for pattern usage

I already blogged about Dependency injection and service locator patterns and about Model View Presenter design pattern, but I’ll be blogging again about them and about some other patterns with some “real world” problems scenarios which could clarify what kind of problems some pattern could solve. The intention of those examples are not to be “real” “real world examples” but to be still abstracted examples which could discover you use cases when you could use some pattern

So, stay tuned

Composite pattern – persistent control tree problem

To get a very detail explanation of what this pattern stands for check out the Armen’s blog – Composite where he posted very detail article about pattern illustrated with one nice example

Problem – use case

The use case of the problem we would be solving in this example is next one:

We have a web page with fie different controls. The web page is organized in a web parts style, in the sense every control encapsulates the persistence logic inside of it.

When user clicks on a Save button of the page, page just commands to controls to persist the data without the knowledge what and how is been persisted.

The controls are named ControlA, ControlB, ControlC, ControlD and ControlE.

ControlB persistence requires that controlC and controlD would be persisted successfully first

ControlA persistence requires that ControlB and ControlE would be persisted successfully first

So, there’s a tree structure

ControlA
    ControlB
        ControlC
        ControlD
     ControlE

Why composite pattern?

Composite pattern in short is a pattern where some type has a member which is a collection of the same element.

So, if I would have an Interface IPersistable with a property of IPersistable collection type and bool Persist() method

image

If we would take a look at our problem we would see that this interface fits problem description: a bunch of controls which can be (or not) dependable on other controls. Our interface is: something which implements an IPersistable interface with a collection of something implementing the same interface.

Rule of thumb

Usage of composite pattern is usually appropriate whenever there are hierarchical tree structures where all the tree nods are of the same type.

Problem – solution example

Class Diagram of the solution

image

BaseControl

We would first implement the IPersistable interface on a BaseControl class which would also inherit from UserControl.
BaseControl would implement the IPersistable interface by defining the ICollection<IPersistable> field and expose it through the getter property named Dependencies.
BaseControl would implement the IPersistable method Persist() by defining it as virtual method which base implementation would just iterate through the Dependencies collection and call Persist() method on each collection member.

BaseControl code example:

 

   1: public abstract class BaseControl : UserControl, IPersistable
   2: {
   3:     private readonly ICollection<IPersistable> _dependencies 
   4:         = new List<IPersistable>();
   5:  
   6:     #region IPersistable Members
   7:  
   8:     /// <summary>
   9:     /// Defines list of controls which has to be persisted 
  10:     /// successfully before this control can be persisted
  11:     /// </summary>
  12:     public ICollection<IPersistable> Dependencies
  13:     {
  14:         get { return _dependencies; }
  15:     }
  16:  
  17:     /// <summary>
  18:     /// Method which would implement control peristing
  19:     /// </summary>
  20:     /// <returns></returns>
  21:     public virtual bool Persist()
  22:     {
  23:         foreach (IPersistable dependecy in _dependencies)
  24:         {
  25:             if (!dependecy.Persist())
  26:             {
  27:                 // something went wrong in saving lower leafs
  28:                 return false;
  29:             }
  30:         }
  31:         return true;
  32:     }
  33:  
  34:     #endregion
  35:  
  36: }

Controls implementation

Every web control would inherit from BaseControl and override its base implementation of the Perist() method.

Implementation would first call the base.Persist() which would caused the BaseControl to start iterating through the dependencies and persist them. If all the dependencies would persist successfully their state base.Perist() would return true value. Then the control itself could persist itself.

The same logic is implemented in all controls

ControlA implementation example

   1: public partial class ControlA : BaseControl
   2: {
   3:     /// <summary>
   4:     /// Persisting the control level information
   5:     /// </summary>
   6:     /// <returns></returns>
   7:     public override bool Persist()
   8:     {
   9:         bool areAllChildControlsPeristedSuccessfully = base.Persist();
  10:         if (!areAllChildControlsPeristedSuccessfully)
  11:         {
  12:             Response.Write("<br />Some of the dependent controls of ControlA failed to perist");
  13:             return false;
  14:         }
  15:  
  16:         // do something specific to peristsance of this
 control
  17:         Response.Write("<br />Save completed in ControlA");
  18:         return true;
  19:     }
  20: }

Page implementation

Now when we have defined composite behaviors of controls we have only to define the dependency structures of controls and form a composite tree. That would be done on a page level by simply setting the values of Dependencies property of every control.
(This is a setter type of dependency injection which I covered in Dependency injection and service locator patterns  and I would be covering in separate article from “real world patterns” series of articles)

Page code example

   1: protected void Page_Load(object sender, EventArgs e)
   2: {
   3:     // defining dependencies of ControlB
   4:     ControlB1.Dependencies.Add(ControlC1);
   5:     ControlB1.Dependencies.Add(ControlD1);
   6:     
   7:     // defining dependencies of ControlA
   8:     ControlA1.Dependencies.Add(ControlB1);
   9:     ControlA1.Dependencies.Add(ControlE1);
  10: }

Testing the solution

We would add a button on the page and inside of that button we would initiate persistence

 

protected void Button1_Click(object sender, EventArgs e)
{
   ControlA1.Persist();
}

And the result:

Result

Problem solved!

To download source code click here: Example source code

Advertisements

Posted on July 23, 2007, in Uncategorized. Bookmark the permalink. 1 Comment.

  1. Nice post. I was looking for something like this for quite some time now. Even posted a question on stackoverflow with no answer yet.
    stackoverflow.com/…/best-way-to-design-recursively-dynamic-asp-net-web-controls
    I think this can really help me out. 😉

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: