单件模式

特点:
     1:单例类只能有一个实例。
     2:单例类必须自己创建自己的唯一实例。
     3:单例类必须给所有其它对象提供这一实例。

应用:
      每台计算机可以有若干个打印机,但只能有一个Printer Spooler,避免两个打印作业同时输出到打印机。 
   一个具有自动编号主键的表可以有多个用户同时使用,但数据库中只能有一个地方分配下一个主键编号。否则会出现主键重复。


代码实现:

public sealed class Singleton
{
    Singleton()
    
{
    }


    
public static Singleton Instance
    
{
        
get
        
{
            
return Nested.instance;
        }

    }

    
    
class Nested
    
{
        
// Explicit static constructor to tell C# compiler
        
// not to mark type as beforefieldinit
        static Nested()
        
{
        }


        
internal static readonly Singleton instance = new Singleton();
    }

}


 

代码

    /// <summary>
    
/// 泛型实现单例模式
    
/// </summary>
    
/// <typeparam name="T">需要实现单例的类</typeparam>

    public class Singleton<T> where T : new()
    
{
        
/// <summary>
        
/// 返回类的实例
        
/// </summary>

        public static T Instance
        
{
            
get return SingletonCreator.instance; }
        }


        
class SingletonCreator
        
{
            
internal static readonly T instance = new T();
        }

    }

//某一个类
public class Test
{
    
private DateTime _time;

    
public Test()
    
{
        System.Threading.Thread.Sleep(
3000);
        _time 
= DateTime.Now;    
    }


    
public string Time
    
{
        
get return _time.ToString(); }
    }

}

//调用
        
// 使用单例模式,保证一个类仅有一个实例
        Response.Write(Singleton<Test>.Instance.Time);
        Response.Write(
"<br />");
        Response.Write(Singleton
<Test>.Instance.Time);
        Response.Write(
"<br />");

        
// 不用单例模式
        Test t = new Test();
        Response.Write(t.Time);
        Response.Write(
"<br />");
        Test t2 
= new Test();
        Response.Write(t2.Time);
        Response.Write(
"<br />");


特别提醒的是由于静态方法是线程共享的所以数据库连接字符串不能是静态类型.
 

原文地址:https://www.cnblogs.com/tommyli/p/1032378.html