单例模式(懒汉式、饿汉式)


//
单例模式饿汉式 class Order{ //1.私有化类的构造器 private Order(){ } //2.声明当前类对象,没有初始化 //4.此对象必须声明为staitc的 private static Order instance = null; //3.声明public static 的返回当前类对象房方法 public static Order getInstance(){ if(instance == null){ instance = new Order(); } return instance; } }
//单例模式懒汉式
class lazy{
    //1.私有化构造器
    private lazy(){

    }
    //2.内部提供一个当前类的实例
    //4.实例必须静态化
    private static  lazy la;
    //3.提供公共的静态方法,返回当前类对象
    public static  lazy getInstance(){
        if (la == null){
            la = new lazy();
        }
        return la;
    }

}

2.单例模式主要应用场景

 

3.单例模式优点

 

posted on 2022-06-23 12:13  Red_kucha  阅读(11)  评论(0)    收藏  举报

导航