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.