A few nights ago I was playing with the implementation of lambda expressions in C#3, and started to wonder how they could be used to lighten up some of the GoF patterns… An interesting, but probably useless outcome of the process was this was the ‘function container,’ which can be used to ‘cheaply’ implement factories.
Each factory gets its own creation delegate, a function signature that produces the product of the factory from some initialisation arguments:

// Person is a POCO
delegate Person PersonFactory(string name);

This delegate can be implemented using a lambda expression, method or anonymous delegate, e.g.:

name => new Person(name)

In this simple form it is a snap to add factories external to each of the domain object types, but the opportunity to inject more complex creation logic is maintained. To tie together the resulting proliferation of delegate expressions, a typed container is used:

FunctionContainer factories = new FunctionContainer();
factories.RegisterFunction<PersonFactory>(name => new Person(name));

Later the factories can be retrieved from the container and called:

Person newPerson = factories.Func<PersonFactory>().Call("Henry");

The ‘Call’ syntax is a bit of hacky generic magic that makes me think back to C++ days past… :) The return type of the FunctionContainer.Func() method is not the registered delegate itself, but a wrapper exposing the delegate through a property named Call:

// ICallable<TDelegate> exposes a TDelegate through a property called Call
ICallable<TDelegate> Func<TDelegate>();

I can’t see myself putting this to use in a real application, but the (often fairly inconvenient) fact that delegates in .NET get their own type regardless of their signature can obviously be put to some kind of use. More to come I guess!
By the way, the ‘automatic factory’ just coincidentally gave its name to this blog by reminding me of a neat story of the same title by Philip K. Dick!