Tuesday, February 17, 2009

Solving the Late Binding Dilemma With the Factory Pattern

The scenario: Create an instance of a class polymorphically by evaluating a string at runtime.

This could be done by calling Type.GetType("typename"), but this will only work if the type in question is COM visible. For example,

Dim oExcell as Object = Type.GetType("Excel.Application")

is the typical way of getting a reference to an Excel object. But if you want to create an instance of a custom class, there's a lot of complexity that you will need to add to your project. Why can't it just work? (How many times have I found myself asking *that* question?) The following is a concise alternative that will solve the problem.

Here, we have a number of different report classes all based on a common base class. The PrintJobReportFactory class will return the correct instance based on a string.

While most of the time, using hard-coded strings to control program flow impedes scalability, as Tom Cruise said "You know, Bill, there's one thing I learned in all my years. Sometimes you just gotta say, "What the ...".

Of course, he also said "Porche, there is no substitute" to which I would answer with "Mustang GT 500".



Public Class PrintJobReportFactory
Public Shared Function GetReportInstance(ByVal type As String) As PrintJobBase

Dim retVal As PrintJobBase = Nothing
Select Case type
Case "WebDenialsStud"
retVal = New WebDenial()

Case "WebDenialsCoBor"
retVal = New WebDenial()

Case "WebCertifications"
retVal = New WebCertification()

Case "WebApprovals"
retVal = New WebDisclosers()

Case Else
retVal = Nothing
End Select

Return retVal
End Function
End Class

No comments:

Post a Comment