In this article we will create an ASP.Net application using Abstract Factory Pattern. Agenda
Previous Articles
What is Abstract Design Pattern?
Why and When to extend Factory method to Abstract Factory Pattern? If you haven't read Factory Method Pattern please go through it first. Let's consider the same example we used for the Factory method pattern. There we had a class called CustomerFactory which creates various customers according to input it gets. Now the Company decides to extend the application and they say, all customers belonging to a specified country (country 1) and who are of Grade1 get a 200 Rs discount and Grade2 customers belonging to another country (country 2) get a discount of 100Rs, and remaining ____. So the CustomerFactory ends up with a code which looks like this:
Client Code
Factory ends up with too many case (or if) conditions, and every new country results in two or more case conditions.
One solution is to create 3 different factories, Country1Factory, Country2Factory and OtherFactory. Which means every new country results in recompilation of client code, also the client needs to be aware of each and every factory.
Abstract Factory Pattern as the solution Here a higher level factory is created which will act as a factory for other factories and those factories will create the final concrete classes as per specifications. The Components involved in the Abstarct Factory Method Pattern are:
Product: IBaseCustomer
Concrete Product: Grade1Customer and Grade2Customer
BaseFactory: CustomerFactory
Concrete Factory: Country1Factory and Country2Factory
Let's modify the previous code. Output Step 1 Create a Base Factory or we can ____ Factory of Factories called CustomerFactory; see:
Step 3
Add a virtual method inside the CustomerFactory for creating final concrete classes; see:
Define concrete factories, and inherit them from base factories i.e, from CustomerFactory; see:
Override virtual methods in concrete factories according to requirements and return final concrete classes; see:
Step 6
Write Client Code
We are done with the third creation pattern, please download the attached zip file for the complete source code. Hope you enjoyed. Keep reading and comments are always welcome.