java学习 类和对象12 单例子模式

内容

(在编程过程中的一些需要下的解决方法,非语法)有些情况下类所需的实例化对象只需要一个。

基本知识

单例子有其中,只学习最常见的两种。

  1. 首先将构造方法私有化>>使得其他类无法进行访问。
  2. 静态属性指向实例(饿汉式)/指向null(暂时)(懒汉式)
  3. public static的 getInstance方法,返回第二步的静态属性>>提供给其他类的访问方式
public class GiantDragon{
    private GiantDragon{  //1
        
    }
    private static GiantDragon insltance= new GianDragon();//2
    
    public static GiantDragon getInstance(){
        return instance;
    }
}
public class GiantDragon{
    private GiantDragon(){//1
        }
	private static GiantDragon insltance;//2
    public static GiantDragon getInstance(){
        if(null==instance){
            instance = new GiantDragon();
        }
        return instance;
    }
}
GiantDragon g1 = GiantDragon.getInstance();//通过调用方法获取唯一对象。

注意事项

懒汉式和饿汉式的区别就在于是否在启动时就实例化对象,为一种取舍。

posted @ 2021-01-19 14:53  TIGO  阅读(58)  评论(0编辑  收藏  举报