抽象工厂模式(Abstract Factory):提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
Abstract1.cs
代码
using System;
using System.Collections.Generic;
using System.Text;
// 抽象工厂模式(Abstract Factory):提供一个创建一系列相关或相互依赖对象的接口
// ,而无需指定它们具体的类。
namespace AbstractFactory
{
class Abstract1
{
}
class Department
{
private int _id;
public int ID
{
get { return _id; }
set { _id = value; }
}
private string _deptName;
public string DeptName
{
get { return _deptName; }
set { _deptName = value; }
}
}
interface IDepartment
{
void Insert(Department department);
Department GetDepartment( int id);
}
class SqlserverDepartment : IDepartment
{
public void Insert(Department department)
{
Console.WriteLine( " 在SQL Server中给Department表增加一条记录 " );
}
public Department GetDepartment( int id)
{
Console.WriteLine( " 在SQL Server中根据ID得到Department表一条记录 " );
return null ;
}
}
class AccessDepartment : IDepartment
{
public void Insert(Department department)
{
Console.WriteLine( " 在Access中给Department表增加一条记录 " );
}
public Department GetDepartment( int id)
{
Console.WriteLine( " 在Access中根据ID得到Department表一条记录 " );
return null ;
}
}
interface IFactory
{
IDepartment CreateDepartment();
}
class SqlserverFactory : IFactory
{
public IDepartment CreateDepartment()
{
return new SqlserverDepartment();
}
}
class AccessFactory : IFactory
{
public IDepartment CreateDepartment()
{
return new AccessDepartment();
}
}
}
Program.cs
代码
using System;
using System.Collections.Generic;
using System.Text;
namespace AbstractFactory
{
class Program
{
static void Main( string [] args)
{
Department dept = new Department();
IFactory factory = new AccessFactory();
IDepartment id = factory.CreateDepartment();
id.Insert(dept);
id.GetDepartment( 1 );
Console.Read();
}
}
}
运行结果:
在Access中给Department表增加一条记录
在Access中根据ID得到Department表一条记录