KARPACH

WEB DEVELOPER BLOG

Simple factory pattern based on interfaces

The main purpose of factory design patterns is to separate an object creation process from a current implementation context. During coding, you use a factory to create objects. Based on incoming parameters factory decides which object to create. You don’t know the exact type of object. Usually, you know either a base abstract class type that created object was inherited from or an interface that created object is implementing. Based on this knowledge you can use an object (call abstract class methods or interface methods). I found a lot of factory pattern examples with an abstract class connection, but none with an interface connection. However, interface connection is most common in commercial factory design pattern implementations. Many developers use Unity Framework or Castle Project (an example of connection based on the interface). Below I’ll show how to implement a factory with an interface connection like it is done in Unity Framework or Castle Project.

Let’s build animal fabric, which would create dog and cat objects. Let’s define ICat and IDog interfaces.

public interface ICat
{        
    string Meow();
}

public interface IDog
{
    string Bark();
    string Sit();
}

Now, let’s define some Dog and Cat classes that implement ICat and IDog interfaces respectively:

public class Cat:ICat
{               
    public string Meow()
    {
        return "Meow meow meow ...";
    }     
}

public class Dog: IDog
{        
 
    public string Bark()
    {
        return "Woof woof woof ...";
    }
 
    public string Sit()
    {
        return "I am sitting.";
    }
 
}

Now let’s create a factory:

public class DefaultFactory
{
    public static T Create<T>()
    {
        if (typeof(T) == typeof(IDog))
        {
            return (T)(IDog)new Dog();
        }
        else
            if (typeof(T) == typeof(ICat))
            {
                return (T)(ICat)new Cat();
            }
            else
            {
                throw new NotImplementedException(String.Format("Creation of {0} interface is not supported yet.", typeof(T)));
            }
    }
}

And here is how you can use it:

IDog dog = DefaultFactory.Create<IDog>();
ICat cat = DefaultFactory.Create<ICat>();
Console.WriteLine(dog.Bark());
Console.WriteLine(dog.Sit());
Console.WriteLine(cat.Meow());

Output:

Woof woof woof …
I am sitting.
Meow meow meow …

Source code for sample project above.

Posted on September 5, 2011 by

Comments

Posted on 11/23/2011 07:53:25 AM by Jaclyn

And I was just wondernig about that too!

Posted on 2/14/2012 12:53:29 AM by Baba

Nice! Don’t forget to care about the visibility of types. Therefore the classes Dog and Cat can be (should be) marked as internal.
Yes, you are right

Posted on 2/7/2014 09:56:03 AM by VCCGeek

Concise and direct, no beating around the bush. Nice job!