抽象工厂模式(Abstract Factory)
抽象工厂模式(Abstract Factory Pattern)是一个超级工厂创建其他工厂。该超级工厂又称为其他工厂的工厂。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。工厂方法模式是为了克服简单工厂模式的缺点而设计出来的,简单工厂模式的工厂类着产品类的增加需要增加额外的代码,而工厂方法模式每个具体工厂类只完成单个实例的创建,它具有很好的可扩展性。但是在现实生活中,一个工厂只创建单个产品比较少,工厂都多元化,一个工厂创建一系列的产品,如果我们要设计这样的系统时,工厂方法模式就不太适用,而使用抽象工厂模式却可以很好地解决。
using System;
namespace ConsoleApplication
{
//一般每个接口或类都写在单独的.cs文件中
//本示例为了执行查看方便才写在一起
public interface IDatabase
{
void Delete();
void Insert();
}
public interface IORM
{
void Delete();
void Insert();
}
//Sqlserver的增删
public class Sqlserver : IDatabase
{
public void Delete()
{
Console.WriteLine("delete data from sqlserver");
}
public void Insert()
{
Console.WriteLine("insert data to sqlserver");
}
}
//Mysql的增删
public class Mysql : IDatabase
{
public void Delete()
{
Console.WriteLine("delete data from Mysql");
}
public void Insert()
{
Console.WriteLine("insert data to Mysql");
}
}
//Sqlserver的增删
public class SqlserverORM : IORM
{
public void Delete()
{
Console.WriteLine("delete data from sqlserver by ORM");
}
public void Insert()
{
Console.WriteLine("insert data to sqlserver by ORM");
}
}
//Mysql的增删
public class MysqlORM : IORM
{
public void Delete()
{
Console.WriteLine("delete data from Mysql by ORM");
}
public void Insert()
{
Console.WriteLine("insert data to Mysql by ORM");
}
}
public interface ICreator
{
IDatabase CreateDatabase();
IORM CreateORM();
}
public class MysqlFactory:ICreator
{
///
/// 负责创建Mysql
///
///
public IDatabase CreateDatabase()
{
return new Mysql();
}
///
/// 负责创建MysqlORM
///
///
public IORM CreateORM()
{
return new MysqlORM();
}
}
public class SqlserverFactory:ICreator
{
///
/// 负责创建Sqlserver
///
///
public IDatabase CreateDatabase()
{
return new Sqlserver();
}
///
/// 负责创建SqlserverORM
///
///
public IORM CreateORM()
{
return new SqlserverORM();
}
}
/*public static class IFactory
{
//根据需求创建
public static Database CreateDatabase(string dbType)
{
Database db = null;
switch (dbType)
{
case "Sqlserver":
db = new Sqlserver();
break;
case "Mysql":
db = new Mysql();
break;
default:
break;
}
return db;
}
}*/
class Program
{
static void Main(string[] args)
{
IDatabase db1 = new SqlserverFactory().CreateDatabase();
db1.Delete();
db1.Insert();
IDatabase db2 = new MysqlFactory().CreateDatabase();
db2.Delete();
db2.Insert();
IORM db3 = new SqlserverFactory().CreateORM();
db3.Delete();
db3.Insert();
IORM db4 = new MysqlFactory().CreateORM();
db4.Delete();
db4.Insert();
//添加新数据库直接添加对应的类即可
Console.ReadKey();
}
}
}