DESKTOP-7D2I5KK_20200905-郎航

问题

如何实现单例模式

解决

饿汉式单例

public final class Earth {
    
    private static final Earth EARTH = new Earth();
    
    private Earth() {
        super();
    }
    public static Earth getInstance() {
        return EARTH ;
    }

}

懒汉式单例(饱汉式)

public final class Moon {
    
    private static Moon single ;
    
    private Moon() {
        super();
    }
    public static Moon getInstance() {
        if( single == null ) { 
            single = new Moon();
        }
        return single ;
    }

}

吐槽

考试考得不行,不是坑太多,还是怪自己太菜啊。

标签

© 2021 成都云创动力科技有限公司 蜀ICP备20006351号-1