小编给大家分享一下Java设计模式中单件模式有什么用,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!
单件模式确保一个类只有一个实例,并提供一个全局访问点
public class Singleton{
private static Singleton uniqueInstance; // 利用一个静态变量来记录Singleton类的唯一实例
private Singleton(){} // 把构造器声明为私有的,只有自Singleton类内才可以调用构造器
// 用getInstance()方法实例化对象,并返回这个实例
public static Singleton getInstance(){
if (uniqueInstance == null){
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
在多线程中以上代码会生成多个实例,所以需要我们对代码进行改进
public class Singleton{
private static Singleton uniqueInstance;
private Singleton(){}
public static synchronized Singleton getInstance(){
if(uniqueInstance == null){
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
通过增加synchronized关键字到getInstance()方法中,我们迫使每个线程在进入这个方法之前,要先等候别的线程离开该方法。也就是说,不会有两个线程可以同时进入这个方法。
public class Singleton{
// 在静态初始化器(static initializai)中创建单件。这样可以保证线程安全(thread sate)
private static Singleton uniqueInstance = new Singleton();
private static Singleton getInstance(){
return uniqueInstance;
}
}
在JVM在加载这个类时马上创建此唯一的单件实例。JVM保证在任何线程访问uniqueInstance静态变量之前,一定创建此实例。
会有两次检查实例是否存在,若不存在则创建实例,若存在则返回
public class Singlenton{
// volatile关键词:当uniqueInstance变量被初始化成Singleton实例时,多个线程正确地处理uniqueInstance变量
private volatile static Singleton uniqueInstance();
private Singleton(){}
public static Singleton getInstance(){
// 检查实例,如果不存在,就进入同步区块
if(uniqueInstance == null){
// 进入区块后,再检查一次。如果仍是null,才创建实例
synchronized (Singleton.class){
if(uniqueInstance == null){
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
Python 的模块就是天然的单件模式,在模块第一次被导入时,会生成.pyc文件,之后再次导入时,就会直接加载之前生成的.pyc文件,不会再次执行模块代码
先创建一个Singleton文件
class Singleton:
def getSingleton:
pass
singleton = Singleton()
在其他文件中导入这个模块,这个类的地址是唯一的
当实例化一个对象时,先调用类的__new__方法 ,默认调用的是父类Object.__new__方法,实例化对象。然后再调用类的__init__方法进行属性的初始化。
我们可以再__new__方法内加一个判断,若实例存在,则不实例化,若不存在,则实例化。
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = object.__new__(cls, *args, **kwargs)
return cls._instance
def __init__(self):
pass
通过装饰器来实现单件模式
def singleton(cls):
# 创建一个私有变量,类型为字典,用来存放类地址的
_instance = {}
def inner():
# 如果类不存在
if cls not in _instance:
# 实例化一个类并存放在字典里
_instance[cls] = cls()
return _instance[cls]
return inner
@singleton
class ClassName(object):
def __init__(self):
pass
class Singleton(object):
def __init__(self, cls):
self._cls = cls # 接受类名
self._instance = {} # 存放类地址
def __call__(self):
if self._cls not in self._instance:
# 实例化类并存放在字典内
self._instance[self._cls] = self._cls()
return self._instance[self._cls]
@Singleton
class ClassName(object):
def __init__(self):
pass
看完了这篇文章,相信你对“Java设计模式中单件模式有什么用”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。