The Abstract Factory Design Pattern is a way for you to be able to get various types or setups for objects by calling the same factory. The result returned from the create method will be determined by the factory type.
For example, let's say we have a factory that creates items to build a house. So we need material to build the floor and walls. But then imagine that those items could be made of various materials and have perhaps unique characteristics. To accomplish that with the abstract factory we can do like this:
- public interface IItemFactory
- {
- IItem CreateWall();
- IItem CreateFloor();
- }
And we would have two factories:
- public class MetalFactory : IItemFactory
- {
- public IItem CreateWall()
- {
- return new MetalWall();
- }
- public IItem CreateFloor()
- {
- return new MetalFloor();
- }
- }
- public class WoodFactory : IItemFactory
- {
- public IItem CreateWall()
- {
- return new WoodWall();
- }
- public IItem CreateFloor()
- {
- return new WoodFloor();
- }
- }
And various types of material:
- public class MetalWall : IItem { }
- public class MetalFloor : IItem { }
- public class WoodWall : IItem { }
- public class WoodFloor : IItem { }
Now we can use this structure. We could have a builder that will build a part of a house and we could determine what materials he will use by passing a factory to it.
- public class Builder
- {
- private IItemFactory itemFactory;
- public Builder(IItemFactory itemFactory)
- {
- this.itemFactory = itemFactory;
- }
- public void BuildFloor()
- {
- this.itemFactory.CreateFloor();
- }
- public void BuildWall()
- {
- this.itemFactory.CreateWall();
- }
- }
We can decide what the house will be built of by specifying which factory the builder will use:
- var metalBuilder = new Builder(new MetalFactory());
- var woodBuilder = new Builder(new WoodFactory());
In a real life example, we could think of Starcraft using this pattern to create a base for each race. So calling:
- player.CreateBase();
Would create a Nexus, Command Center or Hatchet according to the player's race.



Rajeesh MenothPosted Jul 29, 2015, 11:22 PM EDT
Good One
Santhakumar MunuswamyPosted Jun 30, 2015, 10:42 AM EDT
Good one
Sujeet SumanPosted Jun 20, 2015, 12:10 AM EDT
Nice one
Ehsan SajjadPosted Jun 18, 2015, 11:42 PM EDT
at least understandable for me where it can be useful. Thanks
Sibeesh VenuTOP 100Posted Jun 18, 2015, 10:42 PM EDT
Good one.
Debasis SahaTOP 100Posted Jun 18, 2015, 8:45 PM EDT
good one