INTRODUCTION: There are a couple of reasons to have public classes that need to control their own instantiation. First, is the Singleton pattern (read more here), but another is when you have an object that gets instantiated through reflection. Enter that Factory Pattern. Objects that implement the Factory Pattern are known as Object Factories. There may be any number of objects they create, from reflected types to deserialized data. Object Factories are responsible for making sure the object you request is instantiated correctly and ready to work.

A popular reason for the Factory Pattern is Dependency Injection (I will be doing an article on that in the near future). Essentially, Dependency Injection allows you to create an object from a definition stored in some configuration, and assign it to some known contract. The class that does this magic is the Object Factory.

Another popular reason for the Factory Pattern is to allow a polymorphic sub-class to provide it’s own instantiation signature that is separated from the construction of the class hierarchy. An example is in the Entity Framework where the implementation classes for entities contained a CreateEntityName static method to instantiate the entity and ensure that all non-nullable fields are maintained without having to overload the constructor, which is left as a default constructor so that the user could optionally use the object initializer.

Of the two use cases above, the Dependency Injection technique is the most useful, but for sake of brevity, I will use a simple Object Factory to show the mechanics of the pattern in C#.

EXAMPLE

public static class MyFactory
{
  public static ConstructedObject MakeObject(string data)
  {
    // Don't allow an instance without data!
    if(data == null) throw new ArgumentNullException("Data cannot be null.");

    // Create the object and return it.
    return new ConstructedObject { Data = data };
  }
}

// Our constructible class.
public class ConstructedObject
{
  // No constructor defined, so Data must be initialized
  // by the factory.
  public string Data {get; set;}
}

public class Program
{
  public static void Main(string[] args)
  {
    // Check for arguments.
    if(args.Any())
    {
      // Contrived attempt to get a null data.
      var data = args[0].Length > 0 ? args[0] : null;
    
      try 
      {
        // Create the object.
        var obj = MyFactory.MakeObject(data);
 
        // Yay!
        Console.WriteLine(obj.Data);
      }
      catch(ArgumentNullException ane)
      {
        // Boo!
        Console.WriteLine(ane.ToString());
      }
    }
  }
}

CONCLUSION: The Factory Pattern is one of the most useful utility patterns around. In just this simple example I’ve shown how an Object Factory can apply business rules as an object is instantiated. Another use case could be a class with a static method to provide an instance if and only if certain preconditions are met. This would allow the return of a null object instead of throwing an exception. Really, the sky’s the limit for what can be accomplished with a Factory Pattern implementation!