美文网首页
java案例

java案例

作者: emperorxiaomai | 来源:发表于2021-12-18 11:33 被阅读0次

单例模式

  1. 饿汉式(静态常量或静态代码块)
public class StaticSingleton {
    private static StaticSingleton singleton = new StaticSingleton();

    private StaticSingleton(){

    }

    public static StaticSingleton getSingleton(){
        return singleton;
    }
}
  1. 懒汉式(线程安全,同步方法)
public class SynSingleton {
    private static SynSingleton singleton;

    private SynSingleton() {

    }

    public static synchronized SynSingleton getSingleton() {
        if (singleton == null) {
            singleton = new SynSingleton();
        }
        return singleton;
    }
}

  1. 懒汉式(线程安全,双重检查,同步代码块)
public class DoubleCheckSingleton {

    private static volatile DoubleCheckSingleton singleton;

    private DoubleCheckSingleton() {

    }

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

  1. 静态内部类
public class InnerClassSingleton {
    private static InnerClassSingleton singleton;

    private InnerClassSingleton() {

    }

    private static class SingletonInstance {
        private static InnerClassSingleton instance = new InnerClassSingleton();
    }

    public static InnerClassSingleton getInstance() {
        return SingletonInstance.instance;
    }
}

相关文章

网友评论

      本文标题:java案例

      本文链接:https://www.haomeiwen.com/subject/oigwfrtx.html