栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java设计模式-单例模式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java设计模式-单例模式

饿汉式(静态常量)

  1. 构造器私有化 (防止 new 一个对象)
private Singleton(){}
  1. 类的内部创建对象
private final static Singleton instance = new Singleton();
  1. 向外暴露一个静态的公共方法
public static Singleton getInstance(){
return instance;
}
  1. 代码实现
    结论:这种单例模式可用,可能造成内存浪费

饿汉式(静态代码块)

class Singleton{
//构造器私有化
private Singleton(){}

private static Singleton instance;
static{ //在静态代码块中,创建单例对象
instance = new Singleton();
}
//向外暴露一个静态的公共方法
public static Singleton getInstance(){
return instance;
}
}

结论:这种单例模式可用,可能造成内存浪费

懒汉式(线程不安全)

class Singleton{
private static Singleton instance;
//构造器私有化
private Singleton(){}
//提供一个静态的公有方法,当使用到该方法时,才去创建instance
//即懒汉式
public static Singleton getInstance(){
if(null == instance){
instance = new Singleton();
}
return instance;
}
}

结论:在实际开发中,不要使用这种方式

懒汉式(线程安全,同步方法)

class Singleton{
private static Singleton instance;
//构造器私有化
private Singleton(){}
//加入同步代码,解决线程不安全问题
public static synchronized Singleton getInstance(){
if(null == instance){
instance = new Singleton();
}
return instance;
}
}

结论:在实际开发中,不要使用这种方式

懒汉式(线程安全,同步代码块)

class Singleton{
private static Singleton instance;
//构造器私有化
private Singleton(){}
//加入同步代码,解决线程不安全问题
public static Singleton getInstance(){
if(null == instance){
synchronized (Singleton.class){
instance = new Singleton();
}
}
return instance;
}
}

结论:在实际开发中,不能使用这种方式

双重检查

class Singleton{
private static volatile Singleton instance;
//构造器私有化
private Singleton(){}
//加入同步代码,解决线程不安全问题
public static Singleton getInstance(){
if(null == instance){
synchronized (Singleton.class){
if(null == instance){
instance = new Singleton();
}
}
}
return instance;
}
}

结论:在实际开发中,推荐使用这种单例设计模式

静态内部类
类被装载的时候,静态内部类不会立即被装载;静态内部类被装载的时候是线程安全的

class Singleton{

//构造器私有化
private Singleton(){}
//写一个静态内部类,该类中有一个静态属性Singleton
private static class SingletonInstance{
private static final Singleton instance = new Singleton();
}
public static Singleton getInstance(){
return SingletonInstance.instance;
}
}

结论:推荐使用

枚举

enum Singleton{
INSTANCE;
public void method(){
//方法
}
}

结论:不仅能够避免多线程同步问题,而且还能防止反序列化重新创建新的对象。推荐使用

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/424869.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号