Sometimes a separate factory class may not be desired, for
whatever reason. If you like to keep the logic of creating a class within
the same class as the created object, or within another related class, then this
situation is a possibility with the factory method. The factory method is
usually implemented as a static method. For instance, below is a use of
the factory method.
Listing 9
public class DocumentViewer
{
public static DocumentViewer GetViewerInstance()
{
return new DocumentViewer();
}
}
The template method pattern does not have to be declared public;
rather, it could be an internal way to instantiate an object within the project
only. For instance, when loading data from result sets returned by the
data layer, I will often use a static method to instantiate an object with data
from a DataRow, or some other object. I do this because it keeps all of the
logic pertaining to that class within the class definition, which I think makes
it easier to maintain. I created an example for this below.
Listing 10
public static DocumentViewer
{
internal static DocumentViewer CreateFromData(DataRow row)
{
if (row == null)
throw new ArgumentNullException("row");
DocumentViewer viewer = new DocumentViewer();
viewer.Name = row["Name"].ToString();
viewer.Size = (int)row["Size"];
viewer.PPM = !row.IsNull("PPM") ? (int)row["PPM"] : 600;
return viewer;
}
}
All of the logic dealing with DocumentViewer is within the
DocumentViewer class and only internal classes from the project can create a
new document viewer from a row of data. This approach may be more suitable than
a full-blown factory, but if you find yourself creating several static methods
to perform various operations, maybe the factory pattern would be a better
solution and make it more readable.