单例模式(Java,Python)实现

单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例的特殊类。通过单例模式可以保证系统中一个类只有一个实例。

Java实现
1>懒汉式(使用时判断,存在线程安全问题)

public class Singleton
{
        private static Singleton instance;
        private static String name;
        private Singleton()
        {
                this.name = "lanhan";
                System.out.println("I am Singleton of " + this.name);
        }
        public static Singleton getInstance()
        {
                if(instance == null)
                {
                        instance = new Singleton();
                        return instance;
                }
                return instance;
        }
}

2>饿汉式(加载类的时候生成一个实例)

public class SingletonE
{
        //定义一个类变量,缓存实例
        private static SingletonE instance = new SingletonE();
        private static String name;
        private SingletonE()
        {
                this.name = "ehan";
                System.out.println("I am Singleton of " + this.name);
        }
        //保证只有一个实例
        public static SingletonE getInstance()
        {
                        return instance;
        }
}

3>双重锁(解决懒汉式线程安全)

public class SingletonD
{
        //定义一个类变量,缓存实例
        private static SingletonD instance;
        private static String name;

        private SingletonD()
        {
                this.name = "double";
                System.out.println("I am SingletonD of " + this.name);
        }
        //保证只有一个实例
        public static SingletonD getInstance()
        {
                if(instance == null)
                {
                        synchronized(SingletonD.class)
                        {
                                if(instance == null)
                                {
                                        instance = new SingletonD();
                                }
                        }
                }
                return instance;
        }
}

Python实现
1.普通实现

class Signleton(object):
    """docstring for Signleton"""
    __instance = None
    def __new__(cls, *args, **keywords):
        # if not hasattr(cls, '__instance'):
        if cls.__instance is None:
        # if not cls.__instance:
            cls.__instance = super(Signleton, cls).__new__(cls, *args, **keywords)
        print cls.__instance
        return cls.__instance

if __name__ == '__main__':
    A = Signleton()
    B = Signleton()
    assert id(A) == id(B)
    print A == B

2.装饰器实现

def Singleton(cls):  
    _instance = {}  
    def _singleton(*args, **kargs):  
        if cls not in _instance:  
            _instance[cls] = cls(*args, **kargs)  
        return _instance[cls]  
    return _singleton  
@Singleton  
class A(object):  
    a = 1  
    def __init__(self, x = 0):  
        self.x = x  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值