The Abstract Factory pattern provides a way to encapsulate a group of individual factories that have a common theme.

image

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. The client does not know (or care) about which concrete objects it gets from each of these internal factories since it uses only the generic interfaces of their products. This pattern separates the details of implementation of a set of objects from its general usage.

It sounds all a bit complex to you, don’t worry. In fact, it is really simple. Think about database access in general. There you have a whole bunch of database specific commands, for example SqlConnection, SqlCommand, etc. for SQL Server. For Oracle you have OracleConnection and OracleCommand. And surrise, for ODBC you have OdbcConnection and OdbcCommand. These all have the same parent, DbConnection and DbCommand, respectively.

This can be summarized as follows:

Base class SQL Server Oracle Odbc
DbConnection SqlConnection OracleConnection OdbcConnection
DbCommand SqlCommand OracleCommand OdbcCommand
DbDataReader SqlDataReader OracleDataReader OdbcDataReader

Mostly, I use a SQL Database. This corresponds with the following code:

Need I say more?

This post is part of my series on the foundational design patterns in C#. In this series we explore the ancient design patterns and their use in real-world programming situations of today. In these series of posts we explore each pattern and look at simplified real-world C# code that implements the pattern.