Pages

Friday, 10 January 2014

Abstract Factory design pattern - implementation

In this article we are going to see the how to implement the Abstract Factory design pattern in code, Abstract Factory design is creating a abstract class and a abstract method which will return the required instance based on the input parameter type and create a Factory by the static method.

Now in this sample we take a Interface IAnimal which have a method speak, now this is imlpement for many animals cow, dog, lion, shark, octopus.

publicinterfaceIAnimal

{

string Speak();

}

classDog:IAnimal

{

publicstring Speak()

{

return"Bark";

}

}

classLion:IAnimal

{

publicstring Speak()

{

return"Roar";

}

}

classCat:IAnimal

{

publicstring Speak()

{

return"Meow";

}

}

classOctopus:IAnimal

{

publicstring Speak()

{

return"Whack";

}

}

classWhale:IAnimal

{

publicstring Speak()

{

return"No Voice";

}

}Declare the Enum Types

publicenumAnimalType

{

Lion,

Dog,

Cat,

Whale,

Octopus,

}

publicenumFactoryType

{

LandAnimalFactory,

SeaAnimalFactory

}

Now Let we create a Abstract Factory class with static method return the child instance type ,based on the input. Create a Two derived class from the abstract factory as LandAnimalFactory and SeaAnimalFactory

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace AbstractFactoryDesign

{

publicabstractclassAnimalFactory

{

publicabstractIAnimal GetAnimal(AnimalType animalType);

publicstaticAnimalFactory GetAnimalFactory(FactoryType factoryType)

{

switch(factoryType)

{

caseFactoryType.LandAnimalFactory:

returnnewLandAnimalFactory();

caseFactoryType.SeaAnimalFactory:

returnnewSeaAnimalFactory();

default :

returnnull;

}

}

}

}

classLandAnimalFactory:AnimalFactory

{

publicoverrideIAnimal GetAnimal(AnimalType animalType)

{

switch(animalType)

{

caseAnimalType.Cat:

returnnewCat();

caseAnimalType.Dog:

returnnewDog();

caseAnimalType.Lion:

returnnewLion();

default :

returnnull;

}

}

}

classSeaAnimalFactory:AnimalFactory

{

publicoverrideIAnimal GetAnimal(AnimalType animalType)

{

switch(animalType)

{

caseAnimalType.Octopus:

returnnewOctopus();

caseAnimalType.Whale:

returnnewWhale();

default :

returnnull;

}

}

}

I hope from this article you can learn how to implement the abstract factory design pattern in code.