The factory method pattern deals with the problem of creating objects without specifying the exact class of object that will be created. The factory method design pattern handles this problem by defining a separate method for creating the objects, whose subclasses can then override to specify the derived type of object that will be created.
More generally, the term factory method is often used to refer to any method whose main purpose is creation of objects.
This sample requires the following to be installed: Visual Studio 2008. You can checkout a read-only copy of this sample using tortoise from:
http://bakopanos.googlecode.com/svn/trunk/designpatterns/GangOfFour.FactoryMethod
A very simple example: we’ll create a DataFactory class that will be able to map a IDataReader to an Object. The DataFactory is abstract since the subclasses will override the Map method implementation.
public abstract class DataFactory<T>
where T : class, new()
{
public abstract List<T> List();
protected List<T> List(string cmd)
{
var items = new List<T>();
using (var conn = new SqlCeConnection(@"Data Source=Database1.sdf"))
{
conn.Open();
using (var command = new SqlCeCommand(cmd, conn))
{
var reader=command.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read())
{
items.Add(Map(reader));
}
}
}
return items;
}
public abstract T Map(IDataRecord reader);
}
We need to map the database Table Titles to the object Title.
public classTitle
{
public int Id { get; set; }
public stringName { get; set; }
}
The TitleDataFactory class subclasses the DataFactory and overrides the Map method.
public class TitleDataFactory : DataFactory<Title>
{
public override List<Title> List()
{
return List("select * from titles");
}
public override Title Map(IDataRecord reader)
{
int id = (int) reader["id"];
string name = reader["name"] as string;
var item = new Title {Id = id, Name = name};
return item;
}
}
Although the sample is far from a proper ORM implementation it demonstrates well the Factory Method design pattern.
If you are looking for your next ORM tool then this is the wrong place, consider:
EntLib, Spring, ActiveRecord, NHibernate
LinqToSql, EntityFramework, DataSet
any of the many commercial frameworks such as IdeaBlade, DevExpress XPO and so on…
Some sample client code to demonstrate how to use the DataFactory
/// <summary>
/// Entry point into console application.
/// </summary>
static void Main()
{
List<Title> list = new TitleDataFactory().List();
foreach (var title in list)
{
Console.WriteLine(title.Name);
}
// Wait for user
Console.ReadKey();
}
0 comments:
Post a Comment
Post a comment