Saturday, February 5, 2011

From Factory to AbstractFactory


Following last statements in my previous blog, lets consider there is a need to run our application this time with SQL Server Database.

Essential problems we could see is that:
-          The Connection, Statements and Resulset objects now belongs to SQL Server database, so we have family of similar objects; one set belongs to Oracle and other set belongs to SQL Server DB; and lets also assume that application need to run with even MySQl DB, so we have third set of similar object.

Off course in this case we have to create family of similar objects.

Factory method pattern is not going to work here, it is not designed to handle family of similar products.

So now what?

Hmm… AbstractFactory?

Intent of this pattern says:
Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

In below diagram (from GOF Book), lets replace classes to make things more clear.




WidgetFactory -> MyDatabaseObjects (An abstraction that our application uses to create DB objects)
-          CreateScrollBar -> CreateConnection //Returns a Connection object
-          CreateWindow -> CreateStatements //Returns a Statement object
-           
-          MotifWidgetFactory -> SQLServerDatabaseObjects //Returns SQL server db objects
-          PMWidgetFactory -> MySQLDatabaseObjects //Returns MySQL db objects

-          ScrollBar -> Connection (java.sql.Connection)
-          Window -> Statement (java.sql.Statement)

-          PMWindow -> MySQL concrete Statement class
-          MotifWindow -> SQLServer concrete Statement class

-          PMScrollbar -> MySQL concrete Connection class
-          MotifScrollBar -> SQLServer concrete Connection class

So, now you could imagine what happens when we change the driver classes in our application. When you change the database to SQL Server, application uses SQLServer related Factory; similary when you need to use MySQL, application uses MySql related factory.. and when you do this, nowhere in your source code you’re going to specify concrete classes for any of the database objects. (See Intent above)

Hope this makes thing more clear. Write back, If I could be of any help on this topic

No comments:

Post a Comment