设计模式之抽象工厂模式(AbstractFactory)

时间:2022-09-08 20:27:17

抽象工厂模式(Abstract Factory):提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。

Abstract1.cs

设计模式之抽象工厂模式(AbstractFactory)设计模式之抽象工厂模式(AbstractFactory)代码
   
   
   
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

设计模式之抽象工厂模式(AbstractFactory)设计模式之抽象工厂模式(AbstractFactory)代码
   
   
   
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表一条记录