栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java设计模式之单例模式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java设计模式之单例模式

单例模式分为: 饿汉式单例 和 懒汉式单例 、登记式单例
我们这只讲前两种单例!
一、饿汉式单例

package single;


public class Hungry {

    private Hungry() {}

    private static final Hungry single = new Hungry();
    //静态工厂方法
    public static Hungry getInstance() {
        return single;
    }

}

二、懒汉式单例

package single;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;


public class Lazy {
    private Lazy() {
//        synchronized (Lazy.class){
            if(single!=null){
              throw new RuntimeException("不要试图反射破坏异常");
            }
//        }
        System.out.println(Thread.currentThread().getName()+"OK");
    }

    private volatile static Lazy single=null;   //volatile避免指令重排

    //DCL  double check lazy 双重检查锁
    public  static Lazy getInstance() {
        if (single == null) {
            synchronized (Lazy.class){
                if (single == null) {
                    single = new Lazy();   //不是原子性操作
                    
//                    System.out.println(single);
                }
            }
        }
        return single;
    }

  // 多线程并发
  public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//1.
//      for (int i = 0; i < 10; i++) {
//                  new Thread(()->{
//                  Lazy.getInstance();
//                  }).start();
//      }

//2.
//      Lazy s =  Lazy.getInstance();
//      System.out.println(s);
//      Lazy a = Lazy.getInstance();
//      System.out.println(a);

//3.反射
      Lazy instance = Lazy.getInstance();
      Constructor declaredConstructor =  Lazy.class.getDeclaredConstructor(null);
      declaredConstructor.setAccessible(true);
      Lazy instance2 =declaredConstructor.newInstance();

      System.out.println(instance);
      System.out.println(instance2);


  }

}

三、总结

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/695343.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号