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;  
        }          
    }
  • 相关阅读:
    hdu 4403 枚举
    hdu 4405概率dp
    lightoj 1036 dp
    lightoj 1033 区间dp
    lightoj 1032 二进制的dp
    hdu 4293 dp求最大权值不重合区间
    poj 2449 第k短路
    hdu 4284 状态压缩
    hdu4281 区间dp
    poj 2288 tsp经典问题
  • 原文地址:https://www.cnblogs.com/wsZzz1997/p/14581683.html
Copyright © 2011-2022 走看看