Factory Design Pattern – how can I use it more effectively?

If you have already a high-level programming experience with this design-pattern or with dependency injection, just went on using Dependency-Injection Containers (I recommend to read the documentation of Microsoft PRISM with their way of using Unity).

If not, than you can use this design pattern to get your code in a test-harness very easily :) Just keep an eye on the book series “Robert C.Martin”, the guru of how to do clean coding (I recommend to read the book “Agile Principles,Patterns and Practices” before starting with this pattern). Also give a look to the powerfull VS addin “Resharper” from JetBrains.

If you want to know what this pattern is visit this website: http://www.oodesign.com/factory-pattern.html

Now I show you my way of using this pattern (there are many reasons why I do it in this way. You will understand why, when you start using it). The example could be solved also with dependency injection, I know. But without dependency injection container, I think that not all the objects can be created at startup, and then been injected. Sometimes objects needs to be created deep inside in the code-flow. Than you need to use this static factory at most:

I think a perfect class should be derived from its interface. Only in this way you can get the code under test-harness later.


public interface ConfigReader
   Configuration Get();
 public class AppConfigReader : ConfigReader
  public Configuration Get()
     return Settings.Default.Setting;

Because classes should have just some functions, its easy to create an interface for it.

Next step is to replace in your code all the direct dependencies to your class with the interface. That should be easy using the reshaper.

In your code you will find places where a new instance of the class is creaded with new. Find this places. We will replace them with a call to our static factory. The factory looks like this:

public class ConfigReaderFactory : IFactory<ConfigReader>
  internal static IFactory<ConfigReader> Current;
  public static ConfigReader Create()
    if (Current == null)
    Current = new ConfigReaderFactory();
    return Current.Get();
  public ConfigReader Get()
    return new AppConfigReader();

Now replace “new AppConfigReader()” with “ConfigReaderFactory.Create()”. This will call in your production code also the new operator. But when running in test harness you can mock the factory very quick. Lets give a look to the interface IFactory:

public interface IFactory<out T>
  T Get();

The reason to use a central interface factory is, that in your tests you can mock always the same interface IFactory. I use also helper classes for mocking my factories, and because of that its necesary to have just this interface, and not for every factory its own. Now I show you how you can use the benefits in the tests:

public class Application
  public void Initialize()
    var config = ConfigReaderFactory.Create();
    var appStart = new ApplicationStart(config);

The test looks like this:

public void InitialisationTest_setsTheApplicationStart()
  var app = new Application();

In the setup you can now mock the factory and its returns value if desired:

public void SetUp()
  var mockMyConfigFactory = new MockMyParamFactory<ConfigReader>(ref ConfigReaderFactory.Current);
public void TearDown()
  ConfigReaderFactory.Current = null;

And this is the class MockMyFactory:

public class MockMyFactory<T> where T : class
 public IFactory<T> FactoryCurrentToSet { get; set; }
 private readonly Mock<IFactory<T>> _factoryMock;
 private readonly Mock<T> _classMock;
public Mock<IFactory<T>> FactoryMock
 get { return _factoryMock; }
 public Mock<T> ClassMock
 get { return _classMock; }
public MockMyFactory(ref IFactory<T> factoryCurrentToSet)
_factoryMock = new Mock<IFactory<T>>();
 _classMock = new Mock<T>();
 _factoryMock.Setup(f => f.Get()).Returns(_classMock.Object);
 factoryCurrentToSet = _factoryMock.Object;

I hope you can find the purpose of this factory pattern. If you have construcotrs with parameters, you can also use this. Just commend your question if you need help.

To create the fatory class I have created some nice resharper live templates. So you could create them in one second. Try it out and you will see how fast your code gest structure for running under test harness.

About weiss92

Software Developer
This entry was posted in Uncategorized. Bookmark the permalink.

One Response to Factory Design Pattern – how can I use it more effectively?

  1. Awesome! Thanks for this post, it helped me alot.

Leave a Reply

Fill in your details below or click an icon to log in:

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