一、单例模式构造方法一般是私有的,其他类不能直接调用构造方法
1.饿汉式单例
单例模式的成员变量和构造方法都是私有的
//当类被加载时创建对象,线程安全的,未使用就被创建可能会造成资源浪费
public class Test{
//成员变量是私有、静态的
//饿汉式单例的成员变量直接初始化,和懒汉式不同,懒汉式是null
private static Test test=new Test();
//构造方法是私有的
private Test(){
}
public static Test getInstance(){
return test;
}
}
2.懒汉式单例
//按需创建,但是多线程容易创建出多个对象
public class Test {
//静态方法内部变量也是要是静态的,且不进行初始化操作
//volatile 可见行,禁止JVM指令重排序
private volatile static Test test;
//构造方法要是私有的
private Test(){
}
public static Test getInstance(){
if (test==null){
synchronized(Test.class){
//多线程下可能同时多个线程阻塞在synchronized处,
//若不判断null则可能会创建多个test实例
if(test==null){
//使用volatile的原因: