zoukankan      html  css  js  c++  java
  • 设计模式单例模式

    // 饿汉模式
    public class Singleton{
      // 私有化默认构造函数,防止独自创建对象
      private Singleton(){
        
      }
      // 饿汉饿极了,上来直接就开'吃'了,虚拟机启动就创建实例对象
      private static Singleton instance = new Singleton();
      // 返回实例
      public static Singleton getInstance(){
        return instance;
      }
    }
    // 懒汉模式(多线程会出问题)
    public class Singleton{
      // 私有化默认构造函数,防止独自创建对象
      private Singleton(){
        
      }
      // 懒汉比较懒,不创建实例对象,用的时候再创建
      private static Singleton instance;
      
      public static Singleton getInstance(){
        if(instance == null){
           instance = new Singleton();
        }
        return instance;
    }
    // 懒汉双检锁,避免多线程导致并发问题
    pulblic class Singleton{
        private Singleton(){};
    
        private volatile static Singleton instance;
    
        public static Singleton getInstance(){
            if(instance == null){
                Synchronized(Singleton.class){
                      if(instance == null){
                          instance = new Singleton();   
                      }  
                }
            }
            return instance;  
        }          
    }
  • 相关阅读:
    个人总结
    第三次个人作业——用例图设计
    结对项目——第二次作业
    结对项目——第一次作业
    第二次个人编程作业
    第一次个人编程作业
    个人总结
    第三次个人作业——用例图设计
    第二次结对作业
    第一次结对作业
  • 原文地址:https://www.cnblogs.com/wsZzz1997/p/14581683.html
Copyright © 2011-2022 走看看