Introduction
This article shows how to implement the creational Abstract Factory pattern with C# 2.0 and .NET in a real case.
What's a Design Pattern?
A Design Pattern is a general repeatable solution to a commonly occurring problem in software design. A Design Pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations.
What's a Creational Design Pattern
Creational Design Patterns are Design Patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational Design Patterns solve this problem by somehow controlling this object creation.
Purpose
The Abstract Factory provides an interface for creating families of related or dependent objects without specifying their concrete classes.
Structure
- Abstract Factory, declares an interface for operations that create abstract items.
- Concrete Factory, implements the operations for creating concrete item objects.
- Abstract Item, declares an interface for a type of item object.
- Item, defines an item object to be created by the corresponding concrete factory that implements the Abstract Item interface.
- Client, uses interfaces declared by the Abstract Factory and Abstract Item classes.
Let's write the code for the Abstract Factory
This example shows how to create different datasources using the Abstract Factory pattern.
Public interface IDataFactory
{
IData CreateData();
}
public class DataFromDB: IDataFactory
{
public IData CreateData()
{
return new Data("DataBase source");
}
}
public class DataFromFile: IDataFactory
{
public IData CreateData()
{
return new Data("File source");
}
}
public interface IData
{
string GetData();
}
public class Data: IData
{
private string _value;
public Data(string value)
{
_value = value;
}
public string GetData()
{
return _value;
}
}
public class DataSource
{
private IData _data;
public DataSource(DataType dataType)
{
IDataFactory factory;
switch (dataType)
{
case DataType.File:
factory = new DataFromFile();
_data = factory.CreateData();
break;
case DataType.DB:
factory = new DataFromDB();
_data = factory.CreateData();
break;
}
}
public string GetDataFromSource()
{
return _data.GetData();
}
}
public enum DataType
{
File,
DB
}
How to use the Abstract Factory
The following code shows how to call the Abstract Factory from an application client:
DataSource ds = new DataSource(DataType.DB);
string result = ds.GetDataFromSource();
History
This is the first iteration of this code. Please provide any feedback as to whether you have used this or not, or any problems that anyone has found with it!