首先定義一個接口
public interface IDatabase
{
bool Connect(string ConnectString);
bool Open();
bool Command(string SQL);
void Close();
}
重要提醒
然後就是編寫具體的實現類了
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
return true;
}
catch(SqlException)
{
return false;
}
}
public bool Command(string SQL)
{
try
{
command = new SqlCommand(SQL
command
return true;
}
catch(SqlException)
{
return false;
}
}
public void Close()
{
conn
conn
}
}
呵呵
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
return new SqlServer();
case
return new Oracle();
default:
return new SqlServer();
}
}
}
看明白了嗎?好了
public class Client
{
public static void Main()
{
//Get the database information from Web
string DBType = ConfigurationSettings
string DBConnectString = ConfigurationSettings
IDatabase DB = Factory
//Connect the selected database
if(DB
{
Console
return;
}
//Open database
if(DB
{
Console
return;
}
//Execute SQL Command
string SQL =
if(DB
{
//Do something
}
else
{
Console
DB
return;
}
DB
}
}
好了
思考題
作業題
From:http://tw.wingwit.com/Article/program/net/201311/11462.html