Tuesday, May 25, 2010

Abstract Factory Pattern

Abstract Factory Pattern

Available are products AbstractProductA, AbstractProductB,….
 Each of the products encompasses different varieties such as ProductA1, ProductA2… for AbstractProductA and ProductB1, ProductB2… for AbstractProductB. These ProductA1, ProductA2 are referred to as related items.

AbstractFactory simply ensures the creation of products. ConcreteFactory decides which type of product instance need to be created. That is ConcreteFactory1 creates ProductA1 and ProductB1, similarly ConcreteFactory2 creates ProductA2 and ProductB2.

So the core is the client creates an instance of the ConcreteFactory (i.e., ConcreteFactory1 / ConcreteFactory2) which is responsible for the creation of product object from the related varieties of Products.

Thus the client is independent of the product got created. Also note that the Concrete subclass (ConcreteProduct) for the Product is not specified.


While exploring about this pattern, though I understood the concepts clearly with some good examples, I expected a better scenario to stick determined on this pattern. At that time I came across an article that describes Abstract Factory with ADO.Net 2.0.
Namespace: System.Data.Common

Participants mapping
AbstractFactory : DbProviderFactory
ConcreteFactory : SqlClientFactory, OracleClientFactory, OleDbFactory,...
AbstractProduct : DbConnection, DbCommand, DbParameter,...
ConcreteProduct : SqlConnection, OracleConnection, SqlCommand,...


    1     Dim factory As DbProviderFactory = DbProviderFactories.GetFactory("System.Data.SqlClient")
    2     Dim connection As DbConnection = Nothing
    4     connection = factory.CreateConnection()

Line 1 - Creates an instance for SqlClientFactory (ConcreteFactory) for "factory" object. Factory pattern is made use over there which we will discuss later.
Line 2 - Defines "connection" as DbConnection (AbstractProduct).
Line 4 - factory.CreateConnection() returns a new instance SqlConnection{System.Data.SqlClient.SqlConnection} for the specific provider SqlClient.

Simply without specifying the ConcreteProduct - SqlConnection, the instance got created.

For references and more info:
Design Patterns: Elements of Reusable Object-Oriented Software

No comments:

Post a Comment

Creative Commons License
This work by Tito is licensed under a Creative Commons Attribution 3.0 Unported License.