Java中单例模式-CSDN博客

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

什么是单例模式

1. 构造方法私有化
2. 静态属性指向实例
3. public static的 getInstance方法返回第二步的静态属性

饿汉式是立即加载的方式无论是否会用到这个对象都会加载。

package charactor;
 
public class GiantDragon {
 
    //私有化构造方法使得该类无法在外部通过new 进行实例化
    private GiantDragon(){
         
    }
 
    //准备一个类属性指向一个实例化对象。 因为是类属性所以只有一个
 
    private static GiantDragon instance = new GiantDragon();
     
    //public static 方法提供给调用者获取12行定义的对象
    public static GiantDragon getInstance(){
        return instance;
    }
     
}


package charactor;

public class TestGiantDragon {

	public static void main(String[] args) {
		//通过new实例化会报错
//		GiantDragon g = new GiantDragon();
		
		//只能通过getInstance得到对象
		
		GiantDragon g1 = GiantDragon.getInstance();
		GiantDragon g2 = GiantDragon.getInstance();
		GiantDragon g3 = GiantDragon.getInstance();
		
		//都是同一个对象
		System.out.println(g1==g2);
		System.out.println(g1==g3);
	}
}

 懒汉式单例模式与饿汉式单例模式不同只有在调用getInstance的时候才会创建实例

package charactor;

public class GiantDragon {
 
    //私有化构造方法使得该类无法在外部通过new 进行实例化
    private GiantDragon(){        
    }
 
    //准备一个类属性用于指向一个实例化对象但是暂时指向null
    private static GiantDragon instance;
     
    //public static 方法返回实例对象
    public static GiantDragon getInstance(){
    	//第一次访问的时候发现instance没有指向任何对象这时实例化一个对象
    	if(instance == null){
    		instance = new GiantDragon();
    	}
    	//返回 instance指向的对象
        return instance;
    }
     
}

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: Java