PetShop中的Abstract Factory
在PetShop中,用户可以通过修改Web.Config来指定当前使用的数据访问层,
而不用修改任何代码,用到的核心技术为:Abstract Factory + config file
1.配置文件
<appSettings>
<add key=”WebDAL” value=”PetShop.SQLServerDAL”/>
<add key=”OrdersDAL” value=”PetShop.SQLServerDAL”/>
…
</appSettings>
2.在程序中有一个名为DALFactory的assemble,它只提供一个class充当Abstract Factory:
namespace PetShop.DALFactory
{
/// <summary>
/// This class is implemented following the Abstract Factory pattern to
/// create the DAL implementation
/// specified from the configuration file
/// </summary>
public sealed class DataAccess
{
//读取web.config
// Look up the DAL implementation we should be using
private static readonly string path = ConfigurationManager.AppSettings[”WebDAL”];
private static readonly string orderPath = ConfigurationManager.AppSettings[”OrdersDAL”];
private DataAccess() { }
public static PetShop.IDAL.ICategory CreateCategory()
{
string className = path + “.Category”;
return (PetShop.IDAL.ICategory)Assembly.Load(path).CreateInstance(className);
}
public static PetShop.IDAL.IInventory CreateInventory()
{
string className = path + “.Inventory”;
return (PetShop.IDAL.IInventory)Assembly.Load(path).CreateInstance(className);
}
public static PetShop.IDAL.IItem CreateItem()
{
string className = path + “.Item”;
return (PetShop.IDAL.IItem)Assembly.Load(path).CreateInstance(className);
}
public static PetShop.IDAL.IOrder CreateOrder()
{
string className = orderPath + “.Order”;
return (PetShop.IDAL.IOrder)Assembly.Load(orderPath).CreateInstance(className);
}
public static PetShop.IDAL.IProduct CreateProduct()
{
string className = path + “.Product”;
return (PetShop.IDAL.IProduct)Assembly.Load(path).CreateInstance(className);
}
}
}
以上代码逻辑基本相同:
CreateXXX先根据web.config中的信息拼接出一个classname(= config string + XXX),
然后使用CreateInstance生成实例并返回.
3. 在SQLServerDAL和OracleDAL中实现具体的class,实现对某个数据库的访问逻辑
public class Category : ICategory
{
…
}
这样的例子在PatShop中还有好几个.比如:
在web.config中可以个看到
<appSettings>
<add key=”ProfileDAL” value=”PetShop.SQLProfileDAL”/>
…
</appSettings>
代码中相应地可以找到
ProfileDALFactory
IProfileDAL
SQLProfileDAL
OracleProfileDAL
MessagingFactory
CacheDependencyFactory
