最近C#版块中关于模式设计讨论比较多,偶也来参与参与,呵呵,与大家交流一下。
本文就单例模式进行一些讨论,在实际应用中,单例模式是经常需要的一种模式,
如在应用启动时,可以从数据库中读取一些配置,放在单例中,软件运行时,从单
例中获取参数等,以及一些设备通讯控制的应用等。
现假设有这样一个简单应用:
从控制台读取一个字符串,然后将字符串打印在控制台上。
定义两个类:
-
C# code
-
public class TReader // 负责从控制台上读取一串字符 { public string Read() { Console.WriteLine( " Please input a str: " ); return Console.ReadLine(); } } public class TPrinter // 将字符串打印在控制台上。 { public void Print( string str) { Console.WriteLine( " inputed: " + str); } }
很简单,是吧, 但如果这里要求将TReader和TPrinter以单例模式运行,于是TReader的代码就变成
了这个样子,TPrinter也类似.
-
C# code
-
public class TReader { public static TReader Instance { get { if (_Instance == null ) { _Instance = new TReader(); } return _Instance; } } private static TReader _Instance; public string Read() { Console.WriteLine( " Please input a str: " ); return Console.ReadLine(); } } public class TPrinter { public static TPrinter Instance { get { if (_Instance == null ) { _Instance = new TPrinter(); } return _Instance; } } private static TPrinter _Instance; public void Print( string str) { Console.WriteLine( " inputed: " + str); } }
在每个类里各增加一个静态属性,我想说的问题就在这里,
1.单例模式是全局的行为,是类的外部应用,将这种静态属性设计在类里,显得很古怪。
2.两个类里的Instance实现代码几乎完全一模一样,代码重复,很不雅观!
那么怎么改善这种结构呢,答案就是利用C#的 泛型,
定义这样的一个泛型类,将Instance从TReader和TPrinter中提取出来 (含完整代码)。
-
C# code
-
public class G_ < T > where T : class , new () { public static T Instance { get { if (_Instance == null ) { _Instance = new T(); } return _Instance; } set { _Instance = value; } } private static T _Instance; } public class TReader // 负责从控制台上读取一串字符 { public string Read() { Console.WriteLine( " Please input a str: " ); return Console.ReadLine(); } } public class TPrinter // 将字符串打印在控制台上。 { public void Print( string str) { Console.WriteLine( " inputed: " + str); } } class Program // 主程序 { static void Main( string [] args) { string str = G_ < TReader > .Instance.Read(); // 从控制台上读取字符串 G_ < TPrinter > .Instance.Print(str); // 将字符串打印在控制台上 Console.ReadLine(); } }
通过定义这样的一个泛型类,可实现所有类的单例模式,并且设计类时不再需要考虑
是不是要用到单例,提高了代码的可读性。
这样做实际上也有些缺点,如不能阻止在外部创建多个TPrinter或TReader的实例,一定
程度上违背了单例模式的原则。
http://topic.youkuaiyun.com/u/20110419/18/64f16ad6-92a3-420e-8eec-332cfd455da2.html
转载于:https://blog.51cto.com/flydragon0815/668642