单例模式(泛型类)
来源:互联网 发布:c语言实现多线程 编辑:程序博客网 时间:2024/06/10 20:35
在项目开发过程中,经常会涉及到多个采用单例模式的类,对每个类都要进行单例的处理,甚是不爽。
下面使用泛型类解决了这个问题,只要简单继承就可以了,代码如下:
namespace LogHelper{ using System; /// <summary> /// generic for singletons /// </summary> /// <typeparam name="T"></typeparam> public class Singleton<T> where T : new() { protected Singleton() { if (Instance != null) { throw (new Exception("You have tried to create a new singleton class where you should have instanced it. Replace your \"new class()\" with \"class.Instance\"")); } } public static T Instance { get { return SingletonCreator.instance; } } class SingletonCreator { static SingletonCreator() { } internal static readonly T instance = new T(); } }}
//继承单例类namespace LogHelper{ class HelperClass : Singleton<HelperClass> { public HelperClass() { } public double Add(double a, double b) { return a + b; } }}
调用方法:
HelperClass.Instance.Add(1,2);
有关单例模式详细信息请参考:单件模式(Singleton Pattern)
- 单例模式(泛型类)
- 单件模式(单例模式)
- 单例模式/单例(Singleton)
- 单例模式 Singleton(单例)
- 浅析设计模式之单例模式(又名:单值模式、单件模式)
- Android设计模式 单例模式(枚举单例)
- 浅谈单件模式(单例模式--Singleton Pattern)
- 单例模式(singleton)
- 单例(Singleton)模式
- 单例模式(引用)
- 单例模式(Singleton)
- 单例模式(Singleton)
- (一)单例模式
- Singleton(单例)模式
- 单例模式(Singleton)
- 单例模式(Singleton)
- 单例模式(Singleton)
- 单例模式(singleton)
- android 获取SD卡的路径和SD卡内存
- 团队凝聚的核心-兄弟情
- Windows消息
- Java 实现大文件的分割与合并
- 2008.9—2011.1的大学三年
- 单例模式(泛型类)
- oracle 基本操作
- GHD er forskjellige
- 一台主机部署多个mysqld实例方案
- Openssl windows下编译
- CSS style属性大全
- android:Drawable,Bitmap,Canvas和Paint
- xib文件中的绑定关系
- 12、从头学Android之布局之TableLayout表格布局