Design Patterns: Abstract Factory

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:

  1. public interface IItemFactory    
  2. {    
  3.     IItem CreateWall();    
  4.      
  5.     IItem CreateFloor();    
  6. }  

And we would have two factories:

  1. public class MetalFactory : IItemFactory    
  2. {    
  3.     public IItem CreateWall()    
  4.     {    
  5.         return new MetalWall();    
  6.     }    
  7.      
  8.     public IItem CreateFloor()    
  9.     {    
  10.         return new MetalFloor();    
  11.     }    
  12. }    
  13.      
  14. public class WoodFactory : IItemFactory    
  15. {    
  16.     public IItem CreateWall()    
  17.     {    
  18.         return new WoodWall();    
  19.     }    
  20.      
  21.     public IItem CreateFloor()    
  22.     {    
  23.         return new WoodFloor();    
  24.     }    

And various types of material:

  1. public class MetalWall : IItem { }    
  2. public class MetalFloor : IItem { }    
  3.      
  4. public class WoodWall : IItem { }    
  5. 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.

  1. public class Builder    
  2. {    
  3.     private IItemFactory itemFactory;    
  4.      
  5.     public Builder(IItemFactory itemFactory)    
  6.     {    
  7.         this.itemFactory = itemFactory;    
  8.     }    
  9.      
  10.     public void BuildFloor()    
  11.     {    
  12.         this.itemFactory.CreateFloor();    
  13.     }    
  14.      
  15.     public void BuildWall()    
  16.     {    
  17.         this.itemFactory.CreateWall();    
  18.     }    

We can decide what the house will be built of by specifying which factory the builder will use:

  1. var metalBuilder = new Builder(new MetalFactory());    
  2. 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:

  1. player.CreateBase();  

Would create a Nexus, Command Center or Hatchet according to the player's race.

Nexus

Hatchet