设计模式中的其中一种-单例模式

单例模式

  1. 简单理解为,有一个类,只能有一个实例化对象,这就是单例模式。
  2. 节约内存,防止造成内存浪费
话不多说 直接上代码.
/**
* 不处于线程的方式考虑!!!单例模式
*
* Created by zhaiyachao on 2020/10/30.
*/
public class SingletonTest {
    
    
   private Boolean st;
   private Boolean en;
   public static SingletonTest instance=null;

   public SingletonTest() {
    
    
       // 随着构造加载赋值
       this.st = true;
       this.en = false;
   }
   public static SingletonTest getInstance(){
    
    
       if (instance==null){
    
    
           instance=new SingletonTest();
       }
       return instance;
   }
}
  • 思考:
  1. 按照多线程的角度去考虑…! 会产生线程不安全… Why ?
  2. 假设: 两个线程,同时调用getInstance方法. {线程1.与线程2.执行到 if (instance==null) }
    都会重复执行, 起初 instance 为null
  3. 解决的方案有三种
  • 双重加锁
  • 同步锁
  • 简单暴力.直接创建对象
  • 请看一下代码
  • 第一种方案

最为简单粗暴的一个

public class SingletonTest {
    
    
   private Boolean st;
   private Boolean en;
   // 一开始就创建了对象
   public  static SingletonTest instance=new SingletonTest();

   public SingletonTest() {
    
    
       this.st = true;
       this.en = false;
   }
   public static synchronized SingletonTest getInstance(){
    
    
       if (instance==null){
    
    
           instance=new SingletonTest();
       }
       return instance;
   }
}
- 同步锁方式实现
//  多线程的情况下, 调用多次, 效率会慢. 消耗资源
    public static  synchronized SingletonTest getInstance(){
    
    
       if (instance==null){
    
    
           instance=new SingletonTest();
       }
       return instance;
   }
- 双重加锁方式实现
public class SingletonTest {
    
    
  private Boolean st;
  private Boolean en;
  // 交给编译器
  public volatile static SingletonTest instance=null;

  public SingletonTest() {
    
    
      this.st = true;
      this.en = false;
  }
  public static  synchronized SingletonTest getInstance(){
    
    
  // 双重检索的方式
      if (instance==null) {
    
    
          synchronized (SingletonTest.class) {
    
    
              if (instance == null) {
    
    
                  instance = new SingletonTest();
              }
          }
      }
      return instance;
  }
}

其他设计模式. 待续…!

猜你喜欢

转载自blog.csdn.net/qq_43406764/article/details/109380512