c#

位置:IT落伍者 >> c# >> 浏览文章

C#设计模式之简单工厂篇


发布日期:2022年11月24日
 
C#设计模式之简单工厂篇

首先定义一个接口具体名为Idatabase在这个接口中定义好数据库操作的方法名和参数以及返回值本案例中我定义如下方法

public interface 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

{

connOpen();

return true;

}

catch(SqlException)

{

return false;

}

}

public bool Command(string SQL)

{

try

{

command = new SqlCommand(SQLconn);

commandExecuteNonQuery();

return true;

}

catch(SqlException)

{

return false;

}

}

public void Close()

{

connClose();

connDispose();

}

}

呵呵有点长咬着牙读完心里明白了就会很舒服的如果你现在有这种感觉了再接再厉再为Oracle实现类编写具体代码吧依葫芦画瓢大家有空就画一下吧我就画个雏形了

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 WebConfig

string DBType = ConfigurationSettingsAppSettings[DBType];

string DBConnectString = ConfigurationSettingsAppSettings[DBConn];

IDatabase DB = FactorySelectDatabase(DBType);

//Connect the selected database

if(DBConnect(DBConnectString)==false)

{

ConsoleWriteLine(The database {} can@#t be connectedDBType);

return;

}

//Open database

if(DBOpen()==false)

{

ConsoleWriteLine(The database {} can@#t be opened the connect string is {}DBTypeDBConnectString);

return;

}

//Execute SQL Command

string SQL = update Order set price = price * where productID = @#@#;

if(DBCommand(SQL))

{

//Do something

}

else

{

ConsoleWriteLine(The Operator is not success SQL statament is {}SQL);

DBClose();

return;

}

DBClose();

}

}

好了工程峻工了你们明白了没有?

思考题简单工厂的应用场合和局限性?

作业题假如要开发一个多媒体播放器既能用Window MediaPlayer播放又能用RealPlayer播放还能用QuickTime播放具体用什么播放器由客户选择请你画出UML图并写出代码

               

上一篇:C#中datatabel导出excel(三种方法)

下一篇:C#中使用XML基于DOM的案例分析