A Pattern for Switching Factory Method Implementations Dynamically using C# Delegates

I see this as an alternative to the normal IOC patterns such as Service Locator or Dependency Injection. In this pattern, dependency instances are created using a factory method which is actually a delegate.

A delegate in C# is analogous to a function pointer in C or C++ and often used in similar scenarios to anonymous classes in Java. Delegates encapsulate individual method signatures as named types within a class definition. For example, the following code defines a factory method delegate named CreateBookProcessor which declares a method, returning an IProcessBooks implementation, and requiring a Book instance as an argument.

// Declare a delegate type for creating a book processor:
public delegate IProcessBooks CreateBookProcessor(Book book);

This named type can now be used just as you might any declared type within a class. The implication is, a delegate can be used as a method argument or indeed as a property value. I find it’s convenient to expose the delegate as a property, but a basic setter method is just as easy and probably cleaner. Exposing a delegate as a property is as simple as:

// Property to expose the BookProcessor factory method.
public CreateBookProcessor NewBookProcessor { get; set; }

Thus it’s possible to replace the factory method implementation just by setting the property to a new factory method implementation; Lambda’s are really convenient for this. If you’re worried about polluting your business logic with delegate properties (as you probably should be) you can use an interface to hide these class features.

Something as simple as this will replace a book processor factor implementation:

bookManager.NewBookProcessor = (book) => { return new MyBookProcessor(book); }

This will work fine as long as the MyBookProcessor class implements the IProcessBooks interface.  So to complete the pattern it’s just necessary for your class to invoke the factory method through the property any time a new dependency instance is required. Here’s an example:

public void WhoIsTheAuthor(book)
{
  // this looks funny because I’m invoking a property like a method with an argument!
  var processor = NewBookProcessor(book);
  processor.ProcessBook(book);
}

,

  1. Leave a comment

Leave a Reply

Please log in using one of these methods to post your comment:

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: