Python与Java的单例模式

单例模式

题目:设计一个类,我们只能生成该类的一个实例。

  1. 只能在单线程环境(懒汉模式)
public class Singleton{
    private static Singleton singleton = null;
    private Singleton(){}
    public static Singleton getInstance(){
        if (singleton == null){
            singleton = new Singleton();
        }
        return singleton;
    }
}
  1. 可以用于多线程,但效率低,每次通过属性得到实例是,都会试图加上一个同步锁
public class Singleton{
    private static Singleton singleton = null;
    private Singleton(){}
    public static Singleton getInstance(){
        synchronized(Singleton.class){
            if (singleton == null){
                singleton = new Singleton();
            }
        }
        return singleton;
    }
}
  1. 兼顾线程安全和效率的写法
public class Singleton{
    private static volatile Singleton singleton = null;
    private Singleton(){}
    public static Singleton getInstance(){
        if(singleton == null){
            synchronized(Singleton.class){
                if(singleton == null){
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}
  1. 利用静态内部类写法
public class Singleton{
    private static class SingletonHolder{
        private static final Singleton INSTANCE = new Singleton();
    }
    private Singleton(){}
    public static final Singleton getInstance(){
        return SingletonHolder.INSTANCE;
    }
}

这种写法非常巧妙:

  1. 对于内部类SingletonHolder,它是一个饿汉式的单例实现,在SingletonHolder初始化
    的时候会由ClassLoader来保证同步,使INSTANCE是一个真.实例
  2. 由于SingletonHolder是一个内部类,只在外部类的Singleton的getInstance()中被使用,所以它被加载的时机就是在getInstance()方法第一次被调用的时候。

python中实现单例的方法

使用模块

python的模块就是天然的单例模式,因为模块在第一次导入时,会生成.pyc文件,当第二次导入时,就会直接加载.pyc文件,而不会再次执行模块代码。因此,我们只需要把相关的函数和数据定义在一个模块中,就可以获得一个单例对象了。
例如:
singleton.py中代码为

class Singleton:
    def test():
        pass
singleton = Singleton()
from a import singleton

使用装饰器

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:
    a = 1
    def __init__(self,x=0):
        self.x = x

使用类方法

class Singleton:
    def __init__(self):
        pass
    @clasmethod
    def instance(cls,*args,**kwargs):
        if not hasattr(Singleton,"_instance"):
            Singleton._instance = Singleton(*args,**kwargs)
        return Singleton._instance

使用类方法,加锁

import time
import threading

class Singleton:
    _instance_lock = threading.Lock()

    def __init__(self):
        time.sleep(1)
    @classmethod
    def instance(cls,*args,**kwargs):
        with Singleton._instance_lock:
            if not hasattr(Singleton,"_instance"):
                Singleton._instance = Singleton(*args,**kwargs)

            return Singleton._instance
    

基于__new__方法

import threading
class Singleton:
    _instance_lock = threading.Lock()

    def __init__(self):
        pass
    
    def __new__(cls,*args,**kwargs):
        if not hasattr(Singleton,"_instance"):
            with Singleton._instance_lock:
                if not hasattr(Singleton,"_instance"):
                    Singleton._instance = object.__new__(cls)
        return Singleton._instance
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值