欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JAVA设计模式(四)单例模式

程序员文章站 2022-05-30 12:08:13
...
单例模式 确保一个类只有一个实例,并提供一个全局访问站点。

类图:
JAVA设计模式(四)单例模式
            
    
    博客分类: JAVA学习笔记 设计模式java

1.线程不安全的单例模式
/**
 * 单例模式(线程不安全)
 */
public class SingletonTest {

    private static SingletonTest instance;

    private SingletonTest() {
    }

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


2.“懒汉”模式
/**
 * 单例模式(线程安全、每次调用都同步getInstance方法,影响效率)
 */
public class SingletonTest {

    private static SingletonTest instance;

    private SingletonTest() {
    }

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


3.“饿汉”模式
/**
 * 单例模式(线程安全、JVM加载类时马上创建实例)
 */
public class SingletonTest {

    private static SingletonTest instance = new SingletonTest();

    private SingletonTest() {
    }

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


4.双重检查加锁
/**
 * 单例模式(线程安全)
 */
public class SingletonTest {

    private volatile static SingletonTest instance;

    private SingletonTest() {
    }

    public static SingletonTest getInstance() {
        if (instance == null) {
            synchronized (SingletonTest.class) {
                if(instance == null) {
                    instance = new SingletonTest();
                }
            }
        }
        return instance;
    }
}
  • JAVA设计模式(四)单例模式
            
    
    博客分类: JAVA学习笔记 设计模式java
  • 大小: 4.6 KB
相关标签: 设计模式 java