首先定義乙個介面,具體名為idatabase,在這個介面中,定義好資料庫操作的方法名和引數,以及返回值,本案例中我定義如下方法:
public inte***ce idatabase
bool connect(string connectstring);
bool open();
bool command(string sql);
void close();
然後就是編寫具體的實現類了,客戶要求多少不同型別的資料庫,你就定義多少個idatabase的實現類,雖然工作量大了點,可當你看到客戶滿意的笑容時,你心裡也就會有一種由衷的幸福感,好了,sqlserver實現類**如下:
public class sqlserver : idatabase
sqlconnection conn;
sqlcommand command;
public bool connect(string connectstring)
try
conn = new sqlconnection(connectstring);
return true;
catch(sqlexception)
return false;
public bool open()
try
conn.open();
return true;
catch(sqlexception)
return false;
public bool command(string sql)
try
command = new sqlcommand(sql,conn);
command.executenonquery();
return true;
catch(sqlexception)
return false;
public void close()
conn.close();
conn.dispose();
public class oracle : idatabase
public oracle()
public bool connect(string connectstring)
return true;
public bool open()
return true;
public bool command(string sql)
return true;
public void close()
} 嗯,不錯,你有多少種資料庫就編寫不同的實現類**吧,這裡就不贅述了,接下來呢?聰明的讀者一定會想到這個問題:這個介面和這麼多的實現類怎麼用啊?我們再定義乙個稱之為工廠的類,由它來決定選用哪種資料庫為進行操作,這個模擬較簡單:
public class factory
public static idatabase selectdatabase(string databasetype)
switch(databasetype)
case "sqlserver":
return new sqlserver();
case "oracle":
return new oracle();
default:
return new sqlserver();
看明白了嗎?好了,我們該讓尊敬的、永遠高貴的客戶出場了,只有他,唯有他才有決定用哪種資料庫的最高許可權,你看,他這樣用:
public class client
public static void main()
//get the database information from web.config.
idatabase db = factory.selectdatabase(dbtype);
//connect the selected database.
if(db.connect(dbconnectstring)==false)
console.writeline("the database can't be connected.",dbtype);
return;
//open database.
if(db.open()==false)
console.writeline("the database can't be opened, the connect string is .",dbtype,dbconnectstring);
return;
//execute sql command.
string sql = "update order set price = price * 0.07 where productid = '002'";
if(db.command(sql))
//do something...
else
console.writeline("the operator is not success. sql statament is ",sql);
db.close();
return;
db.close();
好了,工程峻工了,你們明白了沒有?
思考題:簡單工廠的應用場合和侷限性?
C 設計模式之簡單工廠篇
首先定義乙個介面,具體名為idatabase,在這個介面中,定義好資料庫操作的方法名和引數,以及返回值,本案例中我定義如下方法 public inte ce idatabase catch sqlexception public bool open catch sqlexception public...
C 設計模式之簡單工廠篇
首先定義乙個介面,具體名為idatabase,在這個介面中,定義好資料庫操作的方法名和引數,以及返回值,本案例中我定義如下方法 public inte ce idatabase catch sqlexception public bool open catch sqlexception public...
C 設計模式之簡單工廠篇
首先定義乙個介面,具體名為idatabase,在這個介面中,定義好資料庫操作的方法名和引數,以及返回值,本案例中我定義如下方法 public inte ce idatabase catch sqlexception public bool open catch sqlexception public...