Introduction:

This article will discuss the Abstract Factory Design Pattern and its real-world applications in .Net Framework 2.0.

About Abstract Factory:

The Abstract Factory Pattern can be used when we want to return one of several related classes of objects, each of which can return several different objects on request. In other words, the Abstract Factory is a factory object that returns one of several groups of classes.

Definition of Abstract Factory Pattern:

Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

Structure of the Abstract Factory Pattern:

abstractfactorystructure.jpg

Abstract Factory Applications From .Net 2.0:

The Abstract Factory is widely used in many applications. Here we will see how the Abstract Factory is used in ADO.NET 2.0.

ADO.NET 2.0 defines a new set of abstract products classes such as DbConnection, DbCommand, DbParameter etc.... At the same time, each product has a concrete product class, like SqlConnection and OralceConnection etc... The XxxConnection classes inherit and implement DbConnection.

Also ADO.NET 2.0 brings a new set of abstract factory classes to help us to implement a Provider-Independent Data Access Layer. Through the use of the DbProviderFactory Class, which is an abstract factory class. The abstract factory, DbProviderFactory, declares a set of CreateXxx Methods, like, CreateConnection, CreateCommand, CreateParamenter etc...

Each of these methods return a specific abstract product, for example CreateConnection returns DbConnection, CreateCommnad return DbCommand etc...

DbProviderFactory has a set of concrete factory classes such as SqlClientFactory, OracleClientFactory etc...These concrete factories implements the CreateXxx methods to return specific products-provider specific classes.

Now have a look at the following UML Class Diagram and compare it with the Abstract Factory structure diagram:

ADO.NETAbstractFactory.jpg

Abstract Factory Participants:

How Abstract Factory participants collaborate:

Normally a single instance of a ConcreteFactory class is created at run-time, a singleton. This concrete factory creates product objects having a particular implementation. To create other product objects, clients should use a different concrete factory. Also we should note that AbstractFactory defers creation of product objects to its ConcreteFactory subclass.

Advantages of Abstract Factory:

Disadvantages of Abstract Factory:

Conclusion:

Abstract Factory Pattern provides a way to encapsulate a group of individual factories that have a common theme. In normal usage, the client software would create a concrete implementation of the abstract factory and then use the generic interfaces to create the concrete objects that are part of the theme.
In our next article, we will talk about simpler Factory Patter, the Simple Factory, and we will see how t use it to create a specific concrete factory.

References: