1

单例设计模式_突围_Cc的技术博客_51CTO博客

 1 year ago
source link: https://blog.51cto.com/u_13560480/5370464
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

单例设计模式

原创

突围_Cc 2022-06-09 14:17:49 ©著作权

文章标签 内部类 单例模式 文章分类 Java 编程语言 阅读数198

1、单例模式特点

一个类只出一个实例;构造器私有化;

2、单例模式有8种写法:

1)、饿汉式(静态常量)

public class Singleton{
private final static Singleton instance = new Singleton();

private Singleton(){}

public static Singleton getInstance(){
return instance;
}
}

优点:在类装载的时候就实例化,避免了线程同步的问题

缺点:在类装载的时候就实例化,不是懒加载,如果从头到尾都没有用过这个实例会造成内存的浪费

在实际开发中可以使用

2)、饿汉式(静态代码)

public class Singleton{
private static Singleton instance;

private Singleton(){}

static{
instance = new Singleton();
}

public static Singleton getInstance(){
return instance;
}
}

优缺点和第一种一样

3)、懒汉式(线程不安全)

public class Singleton{
private static Singleton instance;

private Singleton(){}

public static Singleton getInstance(){
if(instance==null){
instance = new Singleton();
}
return instance;
}
}

优点:懒加载,只能在单线程下使用

缺点:多线程下会产生多个实例

结论:在实际开发中不推荐使用

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

在getInstance()方法上加同步关键字synchronized

public class Singleton{
private static Singleton instance;

private Singleton(){}

public static synchronized Singleton getInstance(){
if(instance==null){
instance = new Singleton();
}
return instance;
}
}

优点:解决了多线程不安全的问题

缺点:效率低,每个线程想要获得类的实例时都需要同步等待

结论:在实际开发中不推荐使用

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

这种方法实际上基于第4中改进,这种也不能起到同步的作用。

public class Singleton{
private static Singleton instance;

private Singleton(){}

public static Singleton getInstance(){
if(instance==null){
synchronized(Singleton.class){
instance = new Singleton();
}
}
return instance;
}
}

结论:在实际开发中不推荐使用

6)、双重检查

public class Singleton{
private static volatile Singleton singleton;
private Singletin(){
}

public static Singleton getInstance(){
if(singleton==null){
synchronized(Singleton.class){
if(singleton==null){
singleton=new Singleton();
}
}
}
return singleton;
}
}

结论:在实际开发中推荐使用

7)、静态内部类

public class Singleton{

private Singletin(){
}
public static Singleton SingletonInstance(){
private static final Singleton INSTANCE=new Singleton();
}
public static Singleton getInstance(){
return SingletonInstance.INSTANCE;

}
}

静态内部类特点:

当Singleton类进行装载的时候,静态内部类是不会被进行装载的;

当我们进行调用Singleton类的getInstance()方法时,SingletonInstance静态内部类才会被装载,并且只会装载一次、同时线程也是安全的;

这种方式即是懒加载、同时也满足线程安全

结论:在实际开发中推荐使用

8)、枚举类

public enum Singleton{
INSTANCE;

public void getMessage(){
System.out.println("hello")
}
}

结论:在实际开发中推荐使用

3、单例模式应用场景

对于一些需要频繁创建销毁的对象,经常用到的对象、工具类对象、频繁访问数据库或文件的对象等。创建对象时耗时过多或耗费资源过多,使用单例模式可以提高系统的性能


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK