To demo how the Factory Method and Abstract Factory patterns work I’ve put together an example in C#. For this example I’ve got 2 different Banks, CIBC, and Royal Bank. Each bank offers a chequing and savings account. Through the use of the Factory Method and Abstract Factory, the sample shows you how to create different types of bank accounts.

“The Factory Method Pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.” - Head First Design Patterns

IBank has a single method called “GetAccountFactory()” that returns a IBankAccountFactory. This allows types that implement the interface to specify what type of bank account factory to construct and return.

public interface IBank 
  {
    string Name { get; }
    IBankAccountFactory GetAccountFactory( );
  }

So CIBC implementation of IBank will return a CIBCBankAccountFactory.

public class CibcBank : Bank, IBank 
  {
    public CibcBank( ) : base( "CIBC" ) {}

    public override IBankAccountFactory GetAccountFactory( ) 
    {
      return new CibcBankAccountFactory( );
    }
  }

“The Abstract Factory Pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.” - Head First Design Patterns

IBankAccountFactory is an abstract factory for creating different types of bank accounts. In my provided example you’ll see that the IBankAccountFactory has two methods defined in it, both of which return an IBankAccount:

public interface IBankAccountFactory 
  {
    IBankAccount CreateChequingAccount( );
    IBankAccount CreateSavingsAccount( );
  }

To create a CIBC chequing account, the client code might look something like this:

IBank bank = new CibcBank( );
  IBankAccountFactory factory = bank.GetAccountFactory( );
  IBankAccount chequingAccount = factory.CreateChequingAccount( );

To create a Royal Bank chequing account, the client code might look something like this:

IBank bank = new RoyalBank( );
  IBankAccountFactory factory = bank.GetAccountFactory( );
  IBankAccount chequingAccount = factory.CreateChequingAccount( );

** Head First Design Patterns (Head First) ** by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra Read more about this title…

DesignPatterns.Factory.zip (9.16 KB)

comments powered by Disqus