The Abstract Factory
The The Abstract Factory is a design pattern which provides an interface for creating families of related or dependent objects without specifying their concrete classes.
The class diagram


The implementation
- Animal Factory :- Abstract Factory
interface AnimalFactory
{
Animal CreateAnimal();
}
- LandFactory, SeaFactory :- Concrete Factories
class LandFactory : AnimalFactory
{
public Animal CreateAnimal()
{
return new Horse();
}
}
class SeaFactory : AnimalFactory
{
public Animal CreateAnimal()
{
return new Seahorse();
}
}
- Animal :- Abstract Product
public interface Animal
{
void Move();
}
- Horse, SeaHorse :- Concrete Product
class Horse : Animal
{
public void Move() {
Console.WriteLine("I Can run very fastly!");
}
}
class Seahorse : Animal
{
public void Move() {
Console.WriteLine("I am moving in the water! He he!");
}
}
- AnimalWorld:- Client
class AnimalWorld
{
private Animal animal;
public AnimalWorld(AnimalFactory animalFactory)
{
animal = animalFactory.CreateAnimal();
}
public void Move()
{
animal.Move();
Console.ReadLine();
}
}
class Program
{
static void Main(string[] args)
{
AnimalFactory animalFactory = createAnimalFactory("land");
AnimalWorld animalWorld = new AnimalWorld(animalFactory);
animalWorld.Move();
}
public static AnimalFactory createAnimalFactory(String type)
{
if ("sea".Equals(type))
return new SeaFactory();
else if ("land".Equals(type))
return new LandFactory();
else
return null;
}
}
References:
http://www.dofactory.com/Patterns/PatternAbstract.aspx#_self2
http://en.wikipedia.org/wiki/Abstract_factory_pattern
2 comments:
Your interfaces should follow the convention of having a little "i" in front of them to make the code more readable. iAnimal as your interface. That'll help distinguish between classes and interfaces.
Post a Comment