/**
单例模式,整个程序只有一个对象
饿汉模式,原因:程序在加载类的时候就会实例化单例对象(体现在第二步)
*/
public class Singleton
{
/*1.将默认构造方法私有化,不允许外界使用构造方法创建实例*/
private Singleton(){};
/*2.实例化一个静态的 对象,整个程序只使用此类该对象*/
private static Singleton instance=new Singleton();
/*3.提供一个方法。供外界获取实例*/
public static Singleton getInstance()
{
return instance;
}
}
单例模式—懒汉模式
/**
* 单例模式—懒汉模式,原因:只有在第一次使用该类对象时才实例化
*/
public class Singleton2
{
/*1.将默认构造方法私有化,不允许外界使用构造方法创建实例*/
private Singleton2(){};
/*2.声明(与饿汉模式区别之处)一个静态的 对象,整个程序只使用此类该对象*/
private static Singleton2 instance;
/*3.提供一个方法。供外界获取实例*/
public static Singleton2 getInstance()
{
if(instance==null) //如果没有该对象,则声明一个(与饿汉模式区别之处)
{
instance=new Singleton2();
}
return instance;
}
}