Thursday, July 15, 2010

The Abstract Factory pattern with C# code example


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
This abstract factory defines method/s for producing the product (in our case Animal). All other concrete factories should implement this/these methods.



interface AnimalFactory
{
Animal CreateAnimal();
}



  • LandFactory, SeaFactory :- Concrete Factories
These are concrete factories, implements different product families. Client can use one of these to create a product (in our case Animal), so client never need to create product object.


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
This is the client and it was written against the abstract factory and it will deal actual factory and the product in the run time. The Program class is having the main method as the entry point



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:

Argrithmag said...

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.

Argrithmag said...
This comment has been removed by the author.