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 IExtensibleObjectinterface. I can use the Extensible pattern to extend the existing Control and add the extensions.

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…

publicclassButtonTextExtension : IExtension<ExtensibleButton>

{

#region IExtension Members

publicvoid Attach(ExtensibleButton owner)

{

owner.Click += newEventHandler(

delegate(Object sender, EventArgs e)

{

owner.Text = "Another Extension";

});

}

publicvoid Detach(ExtensibleButton owner)

{

//Do nothing

}

#endregion

}

And then change the code in the first extension to

publicclassButtonExtension : IExtension<ExtensibleButton>

{

#region IExtension Members

publicvoid Attach(ExtensibleButton owner)

{

owner.Click += newEventHandler (

delegate( Object sender, EventArgs e)

{

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

owner.Extensions.Add(newButtonTextExtension());

});

}

publicvoid Detach(ExtensibleButton owner)

{

//Do nothing here

}

#endregion

}

That’s all.

My form constructor looks like

public Form1()

{

InitializeComponent();

_demoExtBtn.Extensions.Add(newButtonExtension());

}

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