Factory pattern extended with generics
This was obvious a violation of the open closed principle. The abstract version was beter.
But then Generics came to the scene and I was thinking of using them to build my own GenericDaoFactory to loose couple the client code from the instantiation of my data access objects
This is how I did it:
I started by creating an abstract DaoBaseClass with some standard mutual CRUD methods:
public abstract class DaoBaseClass
{
public abstract DTOTypeObj SelectRecord(DTOTypeObj obj);
public abstract void InsertRecord(DTOTypeObj obj);
public abstract void UpdateRecord(DTOTypeObj obj);
public abstract void DeleteRecord(DTOTypeObj obj);
}
We pass in a Data Transfer Object. These objects just contain some state. Here is an example for the Customer DTO
public struct DTOCustomer
{
}// Add all customer transfer properties
private int _customerNumber;
private string _customerAccount;
private int _id;public int CustomerNumber
{}get { return _customerNumber; }
set {_customerNumber = value; }
public string CustomerAccount
{get { return _customerAccount; }}
set { _customerAccount = value;}
The DTO for the employee looks simular. Now let's use the DaoBaseClass and create a DaoCustomer class:
public class DaoCustomer : DaoBaseClass<DTOCustomer>
{
public override void InsertRecord(DTOCustomer obj)public override DTOCustomer SelectRecord(DTOCustomer obj) {
}int customerId = obj.CustomerNumber;
return CustomerService.GetCustomer(obj.CustomerNumber);
{
}CustomerService.InsertCustomer(obj);
}
The other methods are left out to save some space.
What's next? Let's create the generic factory
public class GenericDaoFactory<T, DTO> where T:DaoBaseClass<DTO>, new()
{
private GenericDaoFactory(){}}
public static T CreateDaoInstance()
{T instance = new T();
return instance;
}
The factory is quit simple. We pass in the type of daoObject we want and the factory will create an instance for us. So we are working typesafe. We also have to pass in a DTO type with which the dao object will work.
The only thing we have to do now, is use the factory to create some Dao objects. Like this:
public void DoSomeStuffWithCustomersAndEmployees()
{
DaoCustomer daoCustomer =
GenericDaoFactory<DaoCustomer, DTOCustomer>.CreateDaoInstance();
DTOCustomer dtoCustomer = new DTOCustomer();
dtoCustomer.CustomerNumber = 10;
// Fill in some other data ...
daoCustomer.InsertRecord(dtoCustomer);
DaoEmployee daoEmployee =
GenericDaoFactory<DaoEmployee, DTOEmployee>.CreateDaoInstance();DTOEmployee dtoEmployee = new DTOEmployee();
dtoEmployee.EmployeeNumber = 5;
daoEmployee.DeleteRecord(dtoEmployee);
}
As we can see, we ask the factory to give us a DaoCustomer. It returns us the object and we can start using it. The same happens for the DaoEmployee object.
That's it
Comments are always welcome
Greetings,
G
Labels: Data Transfer Objects, Factory Design Pattern, Generics
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home