Design Pattern - 单例模式

本文深入介绍了单例模式的概念及其在不同编程语言中的实现方法。单例模式能够确保一个类只生成一个实例,并提供了全局访问该实例的方式。文章通过C#和Python的例子详细解释了如何在多线程环境下实现线程安全的单例模式。

单例模式 (singleton),保证一个类仅有一个实例,并提供个访问它的全局访问点。

Singleton pattern provides a mechanism to limit the number of the instances of the class to one. Thus the same object is always shared by different parts of the code. Singleton can be seen as a more elegant solution to global variable because actual data is hidden behind Singleton class interface.
在面向对象代码中, 使用全局函数是比较丑陋的代码, 单例模式可用作为它比较好的替代方案, 该模式提供单点访问机制, 在代码始终都访问到同一个对象.

image

class Singleton
{
    private static Singleton instance; //类变量,对于该类的所有对象共享
    
    private Singleton() {} //私有化构造函数, 客户不能直接生成类对象
    
    public static Singleton GetInstance() //类函数,无需对象,可用类直接调用
    {
        if (instance == null) //只会生成一个对象
        {
            instance = new Singleton();
        }
        return instance;
    }
}

客户代码,

Singleton s = Singleton.GetInstance(); 

对于多线程的singleton, 需要加锁,

class Singleton
{
    private static Singleton instance; 
    private static object syncRoot = new object() //加锁的对象,此时instance对象还没有创建成功,需要一个对象用于加锁
    
    private Singleton() {} 
    
    public static Singleton GetInstance() 
    {
        if (instance == null) //双重锁定, 只有当无instance时才加锁, 提高效率
        {
            lock(syncRoot) //加锁,只有一个线程可以创建对象
             {
                if (instance == null) 
                {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
 

Python has no private constructors we have to find some other way to prevent instantiations.
对于python, singleton模式的实现比较特别, 必须要有个办法在init函数里面阻止其初始化, 这儿采用的办法是抛异常…

class Singleton:
    __single = None
    def __init__( self ):
        if Singleton.__single:
            raise Singleton.__single
        Singleton.__single = self

def Handle():
    try:
        single = Singleton()
    except Singleton, s:
        single = s
    return single    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值