Data Access Application Block Revealed - Factory Methods and Reflection

The other day I talked about the Data Access Application Block and how you can use it in your applications to assist you with ADO.NET.

In particular, I briefly discussed this piece of code:

Data Access Application Block
Database db = DatabaseFactory.CreateDatabase();

string query = "Select *
     from Customers Where CustomerID = @CustomerID";

DBCommandWrapper command = db.GetSqlStringCommandWrapper(query);

command.AddInParameter("@CustomerID", DbType.String, id);

using (IDataReader reader = db.ExecuteReader(command))
{
    // Do Something...
}

 

One of the statements worth understanding a bit better is

 

Factory Method
Database db = DatabaseFactory.CreateDatabase();

Defers the decision of which class to instantiate.

 

If you take a peek at the DAAB source code, that statement is fairly involved on the surface.  It tosses you around to a number of classes and overloaded methods that could be difficult to figure out if you are new to .NET and object-oriented programming.  There is some pretty cool stuff going on there, so I thought I would mimic this statement with an example that is easier to understand.

In the DAAB, Database is an abstract class.  As any abstract class, you cannot create an instance of it.  You can only create concrete classes that derive from Database.  The DAAB currently has 2 such concrete classes: SqlDatabase and OracleDatabase.

So given this piece of knowledge, we can infer that the DatabaseFactory.CreateDatabase() static method will probably return an object of SqlDatabase or OracleDatabase which will be assigned to db.  The actual concrete class will probably be created on-the-fly based on some logic (in this case the settings in the DAAB configuration file).  This type of method is called a Factory Method as it defers the decision of which class to instantiate.

Let's mimic this concept by building our own classes and factory method using an example that is closely related.  First our database classes.  Although they are on a much simpler scale, the classes below follow the same pattern as in the DAAB.  We have an abstract class, called Database, and two concrete classes, called SqlServer and Oracle, which derive from our base class of Database.  I have one simple abstract method in Database, called GetManufacturer().  As an abstract method, all derived classes are required to implement this method and has been done so accordingly.

Now we need to create a Factory Method on a class that creates an instance of SqlServer or Oracle on the fly.  Let's do it similar to the DAAB, but with only one class for simplicity.

Read More

posted on Monday, March 14, 2005 7:55 PM

Main

News

Green Tea

.NET Development

Enterprise Library

Patterns & Practices