Singleton模式


上海教育未来java培训中心网址:www.javaedu.com.cn

QQ:2535279 
QQ:841403798


实现singleton模式:
singleton(单例)设计模式:确保某一个类只能有一个实例.
特点:
1.单例类只能有一个实例.
2.单例类必须自行创建自己的唯一实例.
3.单例类必须自行向所有其他对象提供这个实例.
使用单例模式的必要条件:在一个系统要求一个类只有一个实例的时才应当使用单例模式.(这里设计模式也称为又称GOF模式,中文也可译为四人帮模式)

//饿汉式

public class EagerSingleton{
    private EagerSingleton(){};
    
    public static synchronized EagerSingleton getInstance(){
        return m_instance;
    }

    private static final EagerSingleton m_instance = new EagerSingleton();

}

//饱汉式
public class LazySingleton{

    private LazySingleton(){}

    public static synchronized LazySingleton getInstance(){
        if(m_instance == null){
            m_instance = new LazySingleton();
        }
        return m_instance;
    }

    private static LazySingleton m_instance = null;
}

更多java学习资料尽在网址:www.javaedu.com.cn