在简单工厂模式中讲到存放数据库连接信息,这里将怎样获取连接信息,通常一个应用程序中连接信息应该是全局唯一的,因此,我们想到单例模式。下面我就将怎样写一个单例模式的例子来获取数据库连接信息。简单,我相信大家都能看得懂,我就不再赘述了。代码如下:
(1)存放连接信息的XML文件结构
<?xml version="1.0" encoding="utf-8" ?>
<ConnInfos>
<ConnInfo>
<Name>HR</Name>
<Type>Oralce</Type>
<ConnString>Data Soure=;user=;password=;</ConnString>
</ConnInfo>
<ConnInfo>
<Name>Main</Name>
<Type>SqlServer</Type>
<ConnString>Data Source=;Initial Catalog=;Integrated Security=True</ConnString>
</ConnInfo>
</ConnInfos>
(2)获取连接信息类别
public class ConnManager
{
//存放连接信息
private static Hashtable _connData = Hashtable.Synchronized(new Hashtable());
//连接管理者实例
private static ConnManager _instance = new ConnManager();
private const string Default_Name = "MAIN"; //默认连接名称
private const string File_Name = @"C:\Conn.xml";
//私有构造函数,防止实例化
private ConnManager()
{
LoadData(); //载入数据
}
private void LoadData()
{
BufferedStream bs = null;
try
{
bs = new BufferedStream(new FileStream(File_Name, FileMode.Open, FileAccess.Read));
XmlDocument xd = new XmlDocument();
xd.Load(bs);
XmlNodeList xnl = xd.GetElementsByTagName("ConnInfo");
if (xnl.Count > 0)
{
foreach (XmlNode xn in xnl)
{
if (xn.HasChildNodes)
{
XmlNode n1 = xn.SelectSingleNode("Name");
XmlNode n2 = xn.SelectSingleNode("Type");
XmlNode n3 = xn.SelectSingleNode("ConnString");
string name = n1 != null ? n1.FirstChild.Value : String.Empty;
string type = n2 != null ? n2.FirstChild.Value : String.Empty;
string connStr = n3 != null ? n3.FirstChild.Value : String.Empty;
_connData.Add(name.ToUpper(), new ConnInfo(name, type, connStr));
}
}
}
bs.Close();
}
catch
{
bs.Close();
}
}
public int Count
{
get { return _connData.Count; }
}
public static ConnManager GetInstance()
{
return _instance;
}
public static ConnInfo GetConnInfoByName(string name)
{
string name = name.ToUpper();
if (_connData[name] != null)
{
return _connData[name] as ConnInfo;
}
else
{
return null;
}
}
public static ConnInfo GetConnInfo()
{
return GetConnInfoByName(Default_Name);
}
}