• 设计模式-----单例模式


    单例模式

    可以分为两种:饿汉式和懒汉式两种,饿汉是在系统启动的一开始就初始化好了实例,而懒汉式是在第一次访问的时候才初始化实例。

    饿汉模式

    package org.lltse.pattern.singleton;  
      
    /** 
     * @author lltse 
     * @date 2014-3-13 
     * @ask 饿汉模式 
     * @answer 
     */  
    public class HungerSingleton 
    {  
      
        /** 
         * 一开始就初始化好了实例 
         */  
        private static HungerSingleton instance = new HungerSingleton();  
      
        private HungerSingleton() 
        {  
        }  
      
        public static HungerSingleton getInstance() 
        {  
            return instance;  
        }  
    }  


    懒汉模式

    package org.lltse.pattern.singleton;
    /** 
     *  
     * @author lltse 
     * @date 2014-3-13上午11:41:22 
     * @ask 懒汉模式 
     * @answer 
     */  
    public class LazySingleton 
    {  
    
        private static LazySingleton instance = null;  
      
        private LazySingleton() 
        {  
        }  
      
        public static synchronized LazySingleton getInstance() 
        {  
            if(instance == null)
            {  
                instance = new LazySingleton();  
            }  
            return instance;  
        }  
    }  

     

    多线程环境下的懒汉单例模式

    package org.lltse.pattern.singleton;
    /** 
     * @author lltse 
     * @ask 既满足懒汉模式,又满足只有一个实例,即使多线程环境也是一个实例。
     */
    public class Singleton 
    {       
          
        static class SingletonHolder 
        {       
            static Singleton instance = new Singleton();       
        }       
          
        public static Singleton getInstance() 
        {       
          
            return SingletonHolder.instance;       
          
        }       
    }  
  • 相关阅读:
    sqli-labs(十七)
    sqli-labs(十六)(order by注入)
    sqli-labs(十五)(堆叠注入)
    spring boot热部署
    java之定时任务
    python之字符串函数
    java加载配置文件信息
    python之运算符与基本数据类型
    python基础
    python介绍
  • 原文地址:https://www.cnblogs.com/lltse/p/3640610.html
Copyright © 2020-2023  润新知