【发布时间】:2011-02-16 19:43:31
【问题描述】:
我正在编写一个数据驱动的 WPF 客户端。客户端通常会从查询 SQL 数据库的 WCF 服务中提取数据,但我希望可以选择直接从 SQL 或其他任意数据源中提取数据。
我想出了这个设计,想听听你对它是否是最好的设计的意见。
首先,我们要从 SQL 中提取一些数据对象。
// The Data Object with a single property
public class Customer
{
private string m_Name = string.Empty;
public string Name
{
get { return m_Name; }
set { m_Name = value;}
}
}
然后我计划使用一个所有数据访问层都应该实现的接口。假设也可以使用抽象类。想法?
// The interface with a single method
interface ICustomerFacade
{
List<Customer> GetAll();
}
可以创建 SQL 实现。
// Sql Implementation
public class SqlCustomrFacade : ICustomerFacade
{
public List<Customer> GetAll()
{
// Query SQL db and return something useful
// ...
return new List<Customer>();
}
}
我们还可以创建 WCF 实现。 WCF 的问题在于它不使用相同的数据对象。它会创建自己的本地版本,因此我们必须以某种方式复制详细信息。我想可以使用反射来复制类似字段的值。想法?
// Wcf Implementation
public class WcfCustomrFacade : ICustomerFacade
{
public List<Customer> GetAll()
{
// Get date from the Wcf Service (not defined here)
List<WcfService.Customer> wcfCustomers = wcfService.GetAllCustomers();
// The list we're going to return
List<Customer> customers = new List<Customer>();
// This is horrible
foreach(WcfService.Customer wcfCustomer in wcfCustomers)
{
Customer customer = new Customer();
customer.Name = wcfCustomer.Name;
customers.Add(customer);
}
return customers;
}
}
我还计划使用工厂来决定使用哪个外观。
// Factory pattern
public class FacadeFactory()
{
public static ICustomerFacade CreateCustomerFacade()
{
// Determine the facade to use
if (ConfigurationManager.AppSettings["DAL"] == "Sql")
return new SqlCustomrFacade();
else
return new WcfCustomrFacade();
}
}
这就是 DAL 通常的使用方式。
// Test application
public class MyApp
{
public static void Main()
{
ICustomerFacade cf = FacadeFactory.CreateCustomerFacade();
cf.GetAll();
}
}
感谢您的想法和时间。
【问题讨论】:
-
正如@TomTom 强调的那样,Linq 在生成业务对象和在 SQL 外观中查询方面将节省大量时间。此示例中的对象仅用于说明概念。
标签: c# wcf reflection oop polymorphism