The main purpose of factory design patterns is to separate object creation process from current implementation context. During coding you use factory to create objects. Based on incoming parameters factory decides which object to create. You don't know exact type of the object. Usually you know either base abstract class type that created object was inherited from or interface that created object is implementing. Based on this knowledge you can use object (call abstract class methods or interface methods). I found a lot of factories examples with abstract class connection, but none with interface connection. However interface connection is most common in commercial factory design pattern implementations. Many developers use Unity Framework or Castle Project (example of connection based on interface). Below I'll show how to implement factory with interface connection like it is done in Unity Framework or Castle Project.
Lets build animal fabric, which would create dogs and cats objects. Let's define ICat and IDog interfaces.
public interface ICat
{
string Meow();
}
public interface IDog
{
string Bark();
string Sit();
}
Now, lets define some Dog and Cat classes that implement ICat and IDog interfaces respectevly.
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 lets create 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 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.