请稍侯

单例模式

2016-12-14

单例模式的定义

一个类有且仅有一个实例,并且自行实例化向整个系统提供

单例模式首先要保证构造方法的私有化

饿汉模式

特点是线程安全

public class Singleton {

    private Singleton() {
    }

    private static Singleton instance = new Singleton();

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

懒汉模式

延迟加载,线程不安全

public class Singleton2 {

    private Singleton2() {
        System.out.println("Singleton2 init .........");
    }

    private static Singleton2 instance = null;

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

静态内部类

public class Singleton3 {

    private Singleton3() {

    }

    public static Singleton3 getInstance() {
        Singleton3 instance = Singleton.instance;
        return instance;
    }

    private static class Singleton {
        private static Singleton3 instance = new Singleton3();
    }
}

本文由 vvkee 创作,转载请注明原文链接。