接口到底能不能实例话,在我以前看来是不行的,看了PetShop3后,感觉不是这样的。
数据访问层的DAL工厂:
namespace PetShop.DALFactory {
public class Account
{
public static PetShop.IDAL.IAccount Create()
{
/// Look up the DAL implementation we should be using
string path = System.Configuration.ConfigurationSettings.AppSettings["WebDAL"];
string className = path + ".Account";
// Using the evidence given in the config file load the appropriate assembly and class
return (PetShop.IDAL.IAccount) Assembly.Load(path).CreateInstance(className);
}
}
}
返回的是被转换为IAccount接口的实现了IAccount接口的对象,类似多态。我的理解是这样的:
比如某个类实现了该接口,如类Connection实现了该接口,则Connection类的
实例化对象可以给IConnection接口. 如 IConnection objIConnection = new Connection()
下面具体实现都基于接口进行操作。
在业务逻辑层,他是这么做的,符合上面的想法:
public class Account {
public AccountInfo SignIn(string userId, string password) {
// Validate input
if ((userId.Trim() == string.Empty) || (password.Trim() == string.Empty))
return null;
// Get an instance of the account DAL using the DALFactory
IAccount dal = PetShop.DALFactory.Account.Create();
// Try to sign in with the given credentials
AccountInfo account = dal.SignIn(userId, password);
// Return the account
return account;
}
......