我們先來看看Factory的含義
下面
public interface DataAccess
{
DatabaseType DatabaseType{get;} //數據庫類型
IDbConnection DbConnection{get;} //得到數據庫連接
void Open(); //打開數據庫連接
void Close(); //關閉數據庫連接
IDbTransaction BeginTransaction(); //開始一個事務
int ExecuteNonQuery(string commandText); //執行Sql語句
DataSet ExecuteDataset(string commandText);//執行Sql
}
因為
public sealed class MSSqlDataAccess : AbstractDataAccess
{
……//具體實現代碼
}
public class OleDbDataAccess : AbstractDataAccess
{
……//具體實現代碼
}
public class OracleDataAccess : AbstractDataAccess
{
……//具體實現代碼
}
現在我們已經完成了所要的功能
public sealed class DataAccessFactory
{
private DataAccessFactory(){}
private static PersistenceProperty defaultPersistenceProperty;
public static PersistenceProperty DefaultPersistenceProperty
{
get{return defaultPersistenceProperty;}
set{defaultPersistenceProperty=value;}
}
public static DataAccess CreateDataAccess(PersistenceProperty pp)
{
DataAccess dataAccess;
switch(pp
{
case(DatabaseType
dataAccess = new MSSqlDataAccess(pp
break;
case(DatabaseType
dataAccess = new OracleDataAccess(pp
break;
case(DatabaseType
dataAccess = new OleDbDataAccess(pp
break;
default:
dataAccess=new MSSqlDataAccess(pp
break;
}
return dataAccess;
}
public static DataAccess CreateDataAccess()
{
return CreateDataAccess(defaultPersistenceProperty);
}
}
好了
PersistenceProperty pp = new PersistenceProperty();
pp
pp
pp
pp
DataAccess db= DataAccessFactory
db
……//db
db
或者
DataAccess db= DataAccessFactory
當數據庫發生變化的時候
From:http://tw.wingwit.com/Article/program/ASP/201311/21865.html