创建型 - Singleton单例模式 (转)

作用:
Singleton单例模式目的在于确保一个类只有唯一的一个实例,并且这个唯一实例只有一个全局访问点。它确保类被实例一次,所有这个类的请求都指向这个唯一的实例。另外,这个对象不是在需要的时候才被创建。在Singleton单例模式中,是由单例类来保证这种约束的,而不是客户端通过其他方法实现类的唯一实例。
Role
The purpose of the Singleton pattern is to ensure that there is only one instance of a
class, and that there is a global access point to that object. The pattern ensures that
the class is instantiated only once and that all requests are directed to that one and
only object. Moreover, the object should not be created until it is actually needed. In
the Singleton pattern, it is the class itself that is responsible for ensuring this con-
straint, not the clients of the class.

设计:

UniqueSingletonInstance,私有静态的Singleton类型成员
Singleton(),私有构造函数
GetInstance(),公共获取实例函数
实现:

using  System;
using  System.Collections.Generic;
using  System.Linq;
using  System.Text;

namespace  Singleton
{
    
class  Program
    {
        
static   void  Main( string [] args)
        {
            sigCls sigObj 
=  sigCls.GetInstance();
            Console.WriteLine(sigObj.strData);
            Console.WriteLine(sigObj.GetHashCode().ToString());
           
            Console.ReadLine();
            Console.WriteLine(sigObj.strData);
        }
    }
    
public   class  sigCls
    {
        
private   static  sigCls sigInstance;
        
private  sigCls()
        {
            strData 
=   " Sig " ;
        }

        
public   string  strData
        {
            
get ;
            
set ;
        }
        
public   static  sigCls GetInstance()
        {
            
if  (sigInstance  ==   null )
                sigInstance 
=   new  sigCls();
            
return  sigInstance;
        }

    }
}

 

 

使用场景:

1、确保类仅存在唯一的实例
2、控制访问这个实例在系统中非常关键
3、在类实例以后的会多次使用这个实例
4、由实例化的类来控制单例,而不是由其他机制来控制。

Use the Singleton pattern when …
•  You need to ensure there is only one instance of a class.
•  Controlled access to that instance is essential.
•  You might need more than one instance at a later stage.
•  The control should be localized in the instantiated class, not in some other mechanism.
总结:

有一些类在系统中只存在一个实例才能确保他们的逻辑正确性以及良好的效率。单件模式的使用意图就是:保证一个类仅有一个实例,并提供一个该实例全局的访问点。单例类使用私有的构造函数。Singleton t1 = new Singleton(),编译时告诉我Singleton()不可访问,构造函数是私有的。单线程下的单件模式有几点要注意:
1、 构造器私有化(如果要此类被继承,可以用protected声明构造器)
2、 不要支持IClinieable接口,因为会导致多个对象实例的出现
3、 不能支持序列化
4、 单件模式只考虑了对象创建的管理,没有考虑对象的销毁管理(创建自己的对象,销毁的事交给垃圾回收器吧)
5、 不能应对多线程环境,因为会导致多个对象实例的出现
在多线程下如何实现呢?代码如下:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值