单例模式保证应用中某个实例有且只有一个
比如说:配置文件、工具类、线程池、缓存、日志对象等
单例模式有:1饿汉模式2懒汉模式
下面是
懒汉模式:类加载是不创建实例,用户获取时才真正判断是否为空,如果为空才创建实例
public class Singleton2 {
//构造方法私有化,不允许外面直接创建对象
private Singleton2(){}
//声明类的唯一实例,使用private static 修饰
private static Singleton2 instance;
//提供一个获取实例的方法,使用 public staitc修饰
public static Singleton2 getInstance()
{
if(instance==null)
{
instance=new Singleton2();
}
return instance;
}
}
public class Test {
public static void main(String[] args) {
Singleton2 s3=Singleton2.getInstance();
Singleton2 s4=Singleton2.getInstance();
if(s3==s4)
System.out.println("s1和s2是同一个实例");
else
System.out.println("s1和s2不是同一个实例");
}
}