IFactory介面,定義一個建立訪問User表的抽象的工廠介面
nterface IFactory
{
IUser CreateUser();
IDepartment CreateDepartment();//增加介面的方法
}
SqlServerFactory類,實現IFactory介面,例項化SqlserverUser
class SqlServerFactory :IFactory
{
public IUser CreateUser() {
return new SqlserverUser();
}
public IDepartment CreateDepartment()
{
return new SqlserverDepartment();
}
}
AccessFactory類,實現IFactory介面,例項化AccessUser
class AccessFactory:IFactory
{
public IUser CreateUser() {
return new AccessUser();
}
public IDepartment CreateDepartment()
{
return new AccessDepartment();
}
}
IUser介面,用於客戶端訪問,解除與具體資料庫訪問的耦合
interface IUser
{
void Insert(User user);
User GetUser(int id);
}
SqlserverUser類,用於訪問SQL Server的User
class SqlserverUser :IUser
{
public void Insert(User user) {
Console.WriteLine("在SQL Server中給User表增加一條資訊");
}
public User GetUser(int id) {
Console.WriteLine("在SQL Server中根據Id得到User表中的一條記錄");
return null;
}
}
AccessUser類,,用於訪問Access的User
class AccessUser:IUser
{
public void Insert(User user)
{
Console.WriteLine("在Access中給User表增加一條資訊");
}
public User GetUser(int id)
{
Console.WriteLine("在Access中根據Id得到User表中的一條記錄");
return null;
}
}
User類:
class User
{
private int _id;
public int Id
{
get { return _id; }
set { _id = value; }
}
private int _name;
public int Name
{
get { return _name; }
set { _name = value; }
}
}
以上利用抽象工廠建立了一個使用者的介面,分別可以訪問access資料庫和sql server資料庫,這樣利用情形可以利用工廠方法可以結局,建立一個使用者的工廠,抽象的工廠的用處在哪裡呢?現在來了一個department,也要求可以訪問兩個資料庫,那麼怎麼做呢?這時利用抽象工廠再建立一個department介面:
department類:
class Department
{
private int _id;
public int Id
{
get { return _id; }
set { _id = value; }
}
private string _department;
public string Department1
{
get { return _department; }
set { _department = value; }
}
}
department介面:
interface IDepartment
{
void Insert(Department department);
Department GetDepartment(int id);
}
sqlServeDepartment類,用於訪問SQL Server的Department
class SqlserverDepartment : IDepartment
{
public void Insert(Department department) {
Console.WriteLine("在SQL Server中給Department表增加一條記錄");
}
public Department GetDepartment(int id) {
Console.WriteLine("在SQL Server中根據ID得到deparment表中一條記錄");
return null;
}
}
AccessDepartment類,用於訪問Access的Department
class AccessDepartment :IDepartment
{
public void Insert(Department department)
{
Console.WriteLine("在Access中給Department表新增一條記錄");
}
public Department GetDepartment(int id)
{
Console.WriteLine("在Access中根據id得到department表一條記錄");
return null;
}
}
客戶端呼叫:
static void Main(string[] args)
{
User user = new User();
Department dept = new Department();
IFactory factory = new SqlServerFactory();
IUser iu = factory.CreateUser();
iu.Insert(user);
iu.GetUser(1);
IDepartment id = factory.CreateDepartment();
id.Insert(dept);
id.GetDepartment(1);
Console.Read();
}
執行結果:
理解抽象工廠:
我們再次看看抽象工廠的定義,提供一個建立一系列相關或相互依賴物件的介面,在這個例子,指的是使用者(User)和部門(Department)兩個介面: IUser CreateUser(); IDepartment CreateDepartment(); 沒有指定具體的哪個使用者或者哪個部門的物件.這就是抽象工廠的精髓所在.