简单工厂模式(Simple Factory Pattern)
简单工厂模式定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类。因为在简单工厂模式中用于创建实例的方法是静态(static)方法,又叫做静态工厂方法(Static Factory Method)模式,简单工厂模式是属于创建型模式。
using System;
namespace ConsoleApplication
{
//一般每个接口或类都写在单独的.cs文件中
//本示例为了执行查看方便才写在一起
public interface Database
{
void Delete();
void Insert();
}
//Sqlserver的增删
public class Sqlserver : Database
{
public void Delete()
{
Console.WriteLine("delete data from sqlserver");
}
public void Insert()
{
Console.WriteLine("insert data to sqlserver");
}
}
//Mysql的增删
public class Mysql : Database
{
public void Delete()
{
Console.WriteLine("delete data from Mysql");
}
public void Insert()
{
Console.WriteLine("insert data to Mysql");
}
}
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)
{
Database db1 = IFactory.CreateDatabase("Sqlserver");
db1.Delete();
db1.Insert();
Database db2 = IFactory.CreateDatabase("Mysql");
db2.Delete();
db2.Insert();
Console.ReadKey();
Console.ReadKey();
}
}
}