Monday, October 13, 2008

Using Extensible Object Pattern to extend .NET classes

The Extensible object pattern can be used to extend existing runtime classes with new functionality or to add new state to an object. Mainly used with to extend the functionality of the extensible objects like ServiceHostBase, InstanceContext, OperationContext and IChannelContext in WCF can also be used with other .NET classes and objects.

In this post i will explain how to extend the button control in System.Windows.Forms namespace using the IExtensibleObject interface. I can use the Extensible pattern to extend the existing Control and add the extensions.

public class ExtensibleButton : Button, IExtensibleObject<ExtensibleButton>

{

public ExtensibleButton() : base()

{

this.BackColor = Color.Gold;

this.Extensions = new ExtensionCollection<ExtensibleButton>(this);

}

#region IExtensibleObject Members

public IExtensionCollection<ExtensibleButton> Extensions

{

get;

private set;

}

#endregion

}

And my extension is like

public class ButtonExtension : IExtension<ExtensibleButton>

{

#region IExtension Members

public void Attach(ExtensibleButton owner)

{

owner.Click += new EventHandler (

delegate( Object sender, EventArgs e)

{

MessageBox.Show("Clicked!!!");

});

}

public void Detach(ExtensibleButton owner)

{

//Do nothing here

}

#endregion

}

Now later if I want to add something new to the control like changing a text after the first extension is added. All is to add another extension and then add that to the extensions collection of the new Button control like…

public class ButtonTextExtension : IExtension<ExtensibleButton>

{

#region IExtension Members

public void Attach(ExtensibleButton owner)

{

owner.Click += new EventHandler(

delegate(Object sender, EventArgs e)

{

owner.Text = "Another Extension";

});

}

public void Detach(ExtensibleButton owner)

{

//Do nothing

}

#endregion

}

And then change the code in the first extension to

public class ButtonExtension : IExtension<ExtensibleButton>

{

#region IExtension Members

public void Attach(ExtensibleButton owner)

{

owner.Click += new EventHandler (

delegate( Object sender, EventArgs e)

{

MessageBox.Show("Clicked!!!");

owner.Extensions.Add(new ButtonTextExtension());

});

}

public void Detach(ExtensibleButton owner)

{

//Do nothing here

}

#endregion

}

That’s all.

My form constructor looks like

public Form1()

{

InitializeComponent();

_demoExtBtn.Extensions.Add(new ButtonExtension());

}

You can use the Extensible pattern very effectively in all situations where you need to extend the functionality of an existing class.

1 comment:

Anonymous said...

Very nice post Prajeesh.
I was also looking into extensible object but in context of WCF.
Yes this is pattern and can be used outside WCF context as well