c#设计模式-单例模式

单例模式三种写法:

 

第一种最简单,但没有考虑线程安全,在多线程时可能会出问题,不过俺从没看过出错的现象,表鄙视我……

public class Singleton
{
    private static Singleton _instance = null;
    private Singleton(){}
    public static Singleton CreateInstance()
    {
        if(_instance == null)

        {
            _instance = new Singleton();
        }
        return _instance;
    }
}

第二种考虑了线程安全,不过有点烦,但绝对是正规写法,经典的一叉 

public class Singleton
{
    private volatile static Singleton _instance = null;
    private static readonly object lockHelper = new object();
    private Singleton(){}
    public static Singleton CreateInstance()
    {
        if(_instance == null)
        {
            lock(lockHelper)
            {
                if(_instance == null)
                     _instance = new Singleton();
            }
        }
        return _instance;
    }
}

第三种可能是C#这样的高级语言特有的,实在懒得出奇

public class Singleton
{

    private Singleton(){}
    public static readonly Singleton instance = new Singleton();
}  

一、 单例(Singleton)模式

单例模式的特点:

  • 单例类只能有一个实例。
  • 单例类必须自己创建自己的唯一实例。
  • 单例类必须给所有其它对象提供这一实例。

单例模式应用:

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


二、 Singleton模式的结构:

Singleton模式包含的角色只有一个,就是Singleton。Singleton拥有一个私有构造函数,确保用户无法通过new直接实例它。除此之外,该模式中包含一个静态私有成员变量instance与静态公有方法Instance()。Instance方法负责检验并实例化自己,然后存储在静态成员变量中,以确保只有一个实例被创建。(关于线程问题以及C#所特有的Singleton将在后面详细论述)。


三、 程序举例:

该程序演示了Singleton的结构,本身不具有任何实际价值。

//  Singleton pattern -- Structural example  
using  System;

//  "Singleton"
class  Singleton
{
  
// Fields
  private static Singleton instance;

  
// Constructor
  protected Singleton() {}

  
// Methods
  public static Singleton Instance()
  
{
    
// Uses "Lazy initialization"
    if( instance == null )
      instance 
= new Singleton();

    
return instance;
  }

}


/// <summary>
/// Client test
/// </summary>

public   class  Client
{
  
public static void Main()
  
{
    
// Constructor is protected -- cannot use new
    Singleton s1 = Singleton.Instance();
    Singleton s2 
= Singleton.Instance();

    
if( s1 == s2 )
      Console.WriteLine( 
"The same instance" );
  }

}



四、 在什么情形下使用单例模式:

使用Singleton模式有一个必要条件:在一个系统要求一个类只有一个实例时才应当使用单例模式。反过来,如果一个类可以有几个实例共存,就不要使用单例模式。

注意:

不要使用单例模式存取全局变量。这违背了单例模式的用意,最好放到对应类的静态成员中。

不要将数据库连接做成单例,因为一个系统可能会与数据库有多个连接,并且在有连接池的情况下,应当尽可能及时释放连接。Singleton模式由于使用静态成员存储类实例,所以可能会造成资源无法及时释放,带来问题。


五、 Singleton模式在实际系统中的实现

下面这段Singleton代码演示了负载均衡对象。在负载均衡模型中,有多台服务器可提供服务,任务分配器随机挑选一台服务器提供服务,以确保任务均衡(实际情况比这个复杂的多)。这里,任务分配实例只能有一个,负责挑选服务器并分配任务。

//  Singleton pattern -- Real World example  

using  System;
using  System.Collections;
using  System.Threading;

//  "Singleton"
class  LoadBalancer
{
  
// Fields
  private static LoadBalancer balancer;
  
private ArrayList servers = new ArrayList();
  
private Random random = new Random();

  
// Constructors (protected)
  protected LoadBalancer()
  
{
    
// List of available servers
    servers.Add( "ServerI" );
    servers.Add( 
"ServerII" );
    servers.Add( 
"ServerIII" );
    servers.Add( 
"ServerIV" );
    servers.Add( 
"ServerV" );
  }


  
// Methods
  public static LoadBalancer GetLoadBalancer()
  
{
    
// Support multithreaded applications through
    
// "Double checked locking" pattern which avoids
    
// locking every time the method is invoked
    if( balancer == null )
    
{
      
// Only one thread can obtain a mutex
      Mutex mutex = new Mutex();
      mutex.WaitOne();

      
if( balancer == null )
        balancer 
= new LoadBalancer();

      mutex.Close();
    }

    
return balancer;
  }


  
// Properties
  public string Server
  
{
    
get
    
{
      
// Simple, but effective random load balancer
      int r = random.Next( servers.Count );
      
return servers[ r ].ToString();
    }

  }

}


/// <summary>
/// SingletonApp test
/// </summary>
///

public   class  SingletonApp
{
  
public static void Main( string[] args )
  
{
    LoadBalancer b1 
= LoadBalancer.GetLoadBalancer();
    LoadBalancer b2 
= LoadBalancer.GetLoadBalancer();
    LoadBalancer b3 
= LoadBalancer.GetLoadBalancer();
    LoadBalancer b4 
= LoadBalancer.GetLoadBalancer();

    
// Same instance?
    if( (b1 == b2) && (b2 == b3) && (b3 == b4) )
      Console.WriteLine( 
"Same instance" );

    
// Do the load balancing
    Console.WriteLine( b1.Server );
    Console.WriteLine( b2.Server );
    Console.WriteLine( b3.Server );
    Console.WriteLine( b4.Server );
  }

}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值