工厂模式是解决new的问题,一下举例:利用工厂模式切换多个数据库。
做好这些工作,换数据库只用修改config里的配置即可。
<appSettings>
<add key="type" value="Access"/>
<add key="connectionString" value="server=192.168.5.160;database=sp;uid=sa;pwd=sa"/>
</appSettings>
DataBaseProvider类我最不熟悉啦,贴在下面:
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DataBaseFactory
{
public class DataBase
{
//private static void GetProvider() { }
public static IDataBase _m = null;
public static IDataBase GetInstance()
{
if (_m == null)
{
string type = System.Configuration.ConfigurationSettings.AppSettings.Get("type");
string ns = type + "DataBase.Data," + type + "DataBase";
Type t = Type.GetType(ns);//sqlDataBase.Data(类的全名),sqlDataBase程序集
_m = (IDataBase)Activator.CreateInstance(t, true);
return _m;
}
else
{
return _m;
}
}
}
}