想要了解更多知识或者需要源码学习小程序搜索:源码轻舟文章来源地址https://www.toymoban.com/news/detail-521804.html
- 饿汉式
class Singleton{
private Singleton(){}
private final static Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
}
- 懒汉式
class Singleton{
private Singleton(){}
private static volatile Singleton instance;
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
- 双重监测
class Singleton{
private Singleton(){}
private static volatile Singleton instance;
public static Singleton getInstance(){
if(instance == null){
synchronized(Singleton.class){
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
- 静态内部类(推荐)
class Singleton{
private Singleton(){}
private static class SingletonHelper{
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance(){
return SingletonHelper.INSTANCE;
}
}
- 枚举(推荐)
enum Singleton{
INSTANCE;
}
- 多例模式
class Singleton{
private static Map<String,Singleton> instances = new HashMap<String,Singleton>();
private final int MAX_INSTANCE = 3;
private String name;
private Singleton(String name){
this.name = name;
}
public static Singleton getinstance(String name){
if(!instances.containKey(name) && instance.size() < MAX_INSTANCE){
synchronized(Singleton.class){
if(!instances.containKey(name) && instance.size() < MAX_INSTANCE){
instances.put(name,new Singleton(name));
}
}
}
return instances.get(name);
}
}
- 线程唯一
class Singleton{
private static ThreadLocal<Singleton> instances = new ThreadLocal<>();
private Singleton(){}
public static Singleton getInstance(){
if(instances.get() == null){
synchronized(Singleton.class){
if(instances.get() == null){
instances.add(new Singleton());
}
}
}
return instances.get();
}
}
文章来源:https://www.toymoban.com/news/detail-521804.html
到了这里,关于创建单例模式的7种方式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!