Building an Example
This C# example uses a Customer object from the Northwind sample database mapped to the Customers table in the database.
public class Customer {
// Private data members
String _customerId;
String _companyName;
String _contactName;
String _contactTitle;
public Customer() {}
// Properties for Customer object
public String CustomerId {
get { return _customerId; }
set { _customerId = value;}
}
public String CompanyName {
get { return _companyName; }
set { _companyName = value;}
}
public String ContactName {
get { return _contactName; }
set { _contactName = value;}
}
public String ContactTitle {
get { return _contactTitle; }
set { _contactTitle = value;}
}
}
public interface ICustomerFactory {
// Standard transactional methods for
// single-row operations
void Load(Customer cust);
void Insert(Customer cust);
void Update(Customer cust);
void Delete(Customer cust);
// Query method to return a collection
ArrayList FindCustomersByState(String state);
}
public class CustomerFactory : ICustomerFactory
{
// Standard transactional methods for
// single-row operations
void Load(Customer cust) { /* Implement here */ }
void Insert(Customer cust) { /* Implement here */ }
void Update(Customer cust) { /* Implement here */ }
void Delete(Customer cust) { /* Implement here */ }
// Query method to return a collection
ArrayList FindCustomersByState(String state) {
/* Implement here */
}
}
Below is an example of how a client application will use this code.
public class NorthwindApp
{
static void Main (string[] args) {
Customer cust = new Customer();
CustomerFactory custFactory =
new CustomerFactory();
// Load a customer from Northwind database.
cust.CustomerId = "ALFKI";
custFactory.load(cust);
// Pass on the Customer object
FooBar(cust);
// custList is a collection of
// Customer objects
ArrayList custList =
custFactory.FindCustomersByState("CA");
}
}
In the preceding code, the
load method loads the Customer object from the database based on the
CustomerID, value after which the application can pass it on to any subsystem in the application without exposing the persistence code. Similarly, if you load an ArrayList of Customer objects, you can subsequently pass on the ArrayList, which has no persistence code dependency.
Using the Domain Objects Persistence pattern separates the persistence code from the Customer object, making the Customer object more object-oriented and simpler to understand, because its object model is closer to the data model in the database. In addition, the separation lets you pass Customer objects to different parts of the application (or even to distributed applications through .NET Remoting) without exposing the persistence code.