认识设计模式(一)---单例模式(4)

(一)懒汉式(线程安全,同步方法)

(1)步骤如下:

  1. 构造器私有化(防止new再获取对象)
  2. 类的内部创建对象(但是不急着实例化)
  3. 提供一个公有的静态方法,当使用到这个方法时,先判断对象是不是null,如果为null再去实例化对象instance(饿汉式是调用类就创建对象并且实例化,懒汉式是调用类时创建对象,调用getInstance时对象实例化),并且加入同步synchronized处理的代码,解决线程安全问题(同步就是每次只能有一个线程获取)

(2)单例类代码如下:

class Singleton04{
    //1-构造器私有化
    private Singleton04(){ }
    //2-本类内部创建对象实例
    private static Singleton04 instance;
    //3-提供一个公有的静态方法,当使用到这个方法时,才去创建instance
    // 加入同步synchronized处理的代码,解决线程安全问题(同步就是每次只能有一个线程获取)
    // 懒汉式
    public static synchronized Singleton04 getInstance(){
        if(instance==null){
            instance=new Singleton04();
        }
        return instance;
    }
}

(3)测试类代码如下

public class SingletonTest04 {
    public static void main(String[] args) {
        Singleton04 instance01=Singleton04.getInstance();
        Singleton04 instance02=Singleton04.getInstance();
        System.out.println(instance01==instance02);
        System.out.println("instance01-hashCode="+instance01.hashCode());
        System.out.println("instance02-hashCode="+instance02.hashCode());
    }
}

(二)优缺点分析

  1. 起到了懒加载的效果(调用类的时候只创建对象但是不急着实例化),通过“同步”解决了线程安全的问题
  2. 但是效率太低了
  3. 所以说:在实际开发中,不推荐使用这种方式

(三)与懒汉式(线程不安全)的区别

    public static Singleton03 getInstance(){
        if(instance==null){
            instance=new Singleton03();
        }
        return instance;
    }

改成了

    public static synchronized Singleton04 getInstance(){
        if(instance==null){
            instance=new Singleton04();
        }
        return instance;
    }
发布了41 篇原创文章 · 获赞 5 · 访问量 677

猜你喜欢

转载自blog.csdn.net/weixin_44823875/article/details/104785706
今日推荐