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.
So CIBC implementation of IBank will return a 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:
To create a CIBC chequing account, the client code might look something like this:
To create a Royal Bank chequing account, the client code might look something like this:
** Head First Design Patterns (Head First) ** by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra Read more about this title…