首先定義一個(gè)接口,具體名為idatabase,在這個(gè)接口中,定義好數(shù)據(jù)庫操作的方法名和參數(shù),以及返回值,本案例中我定義如下方法:
public interface idatabase
{
bool connect(string connectstring);
bool open();
bool command(string sql);
void close();
}
重要提醒:“接口一生唯謹(jǐn)慎,定義大事不糊涂”,編寫接口時(shí)一定要考慮周全,并對參數(shù)、返回值進(jìn)行反復(fù)推敲,為什么?因?yàn)樗械膶?shí)現(xiàn)類都是要根據(jù)該接口的規(guī)范進(jìn)行代碼具體編寫,也即接口的定義是公用的,一旦改動(dòng)了接口,后果就是所有的實(shí)現(xiàn)類也都必須相應(yīng)調(diào)整。
然后就是編寫具體的實(shí)現(xiàn)類了,客戶要求多少不同類型的數(shù)據(jù)庫,你就定義多少個(gè)idatabase的實(shí)現(xiàn)類,雖然工作量大了點(diǎn),可當(dāng)你看到客戶滿意的笑容時(shí),你心里也就會有一種由衷的幸福感,好了,sqlserver實(shí)現(xiàn)類代碼如下:
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();
}
}
呵呵,有點(diǎn)長,咬著牙讀完,心里明白了就會很舒服的,如果你現(xiàn)在有這種感覺了,好,再接再厲,再為oracle實(shí)現(xiàn)類編寫具體代碼吧,依葫蘆畫瓢,大家有空就畫一下吧,我就畫個(gè)雛形了:
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()
{
}
}
嗯,不錯(cuò),你有多少種數(shù)據(jù)庫就編寫不同的實(shí)現(xiàn)類代碼吧,這里就不贅述了,接下來呢?聰明的讀者一定會想到這個(gè)問題:這個(gè)接口和這么多的實(shí)現(xiàn)類怎么用啊?我們再定義一個(gè)稱之為工廠的類,由它來決定選用哪種數(shù)據(jù)庫為進(jìn)行操作,這個(gè)類比較簡單:
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();
}
}
}
看明白了嗎?好了,我們該讓尊敬的、永遠(yuǎn)高貴的客戶出場了,只有他,唯有他才有決定用哪種數(shù)據(jù)庫的最高權(quán)限,你看,他這樣用:
public class client
{
public static void main()
{
//get the database information from web.config.
string dbtype = configurationsettings.appsettings["dbtype"];
string dbconnectstring = configurationsettings.appsettings["dbconn"];
idatabase db = factory.selectdatabase(dbtype);
//connect the selected database.
if(db.connect(dbconnectstring)==false)
{
console.writeline("the database {0} can't be connected.",dbtype);
return;
}
//open database.
if(db.open()==false)
{
console.writeline("the database {0} can't be opened, the connect string is {1}.",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 {0}",sql);
db.close();
return;
}
db.close();
}
}
好了,工程峻工了,你們明白了沒有?
思考題:簡單工廠的應(yīng)用場合和局限性?
作業(yè)題:假如要開發(fā)一個(gè)多媒體播放器,既能用window mediaplayer播放,又能用realplayer播放,還能用quicktime播放,具體用什么播放器,由客戶選擇,請你畫出uml圖并寫出代碼。 待續(xù)…
|
新聞熱點(diǎn)
疑難解答
圖片精選