17 June, 2008

Chain of Responsibility: Using a Factory?

 

I've been debating a bit with colleges lately whether it is worthwhile to introduce a Factory responsible of setting up the Chain (constructing the chain). If you have the principle of Separation of Concerns in mind - it actually makes a lot of sense to make a factory responsible of setting up the chain for you (the client to the system!).

In this way - when extending the system by adding new links in the chain, you include this new link by letting it be known to the system one place only; namely the Factory. If you were to make the Client responsible of setting up the chain every time, which by the way is the way the COR pattern was presented by Gang of Four, I feel that you bring in an undesired correlation/binding in the system. Make your software components/elements as loosely coupled as possible!

  /// <summary>
///
Factory producing Chains of Responsibility.
/// </summary>
static class InfoChainFactory
{
/// <summary>
///
Creates the chain and returns the first link.
/// </summary>
/// <returns></returns>
public static GenericHandlerBase<Table> CreateChain()
{
var h1 = new ServerInfoHandler();
var h2 = new FileInfoHandler();
var h3 = new DirectoryHandler();

h1.SetSuccessor(h2);
h2.SetSuccessor(h3);

return h1;
}
}


The Client towards this system is seen below constructing the complete chain (called h1). How the chain is constructed or what it is built of - I as a Client don't know and I don't care.



protected void Page_Load(object sender, EventArgs e)
{
//build handler chain
var h1 = InfoChainFactory.CreateChain();

if (!string.IsNullOrEmpty(Request.QueryString["q"]))
{
tblServer.Rows.Clear();
h1.Handle("q", Request.QueryString["q"], tblServer);
}
}

No comments: