zoukankan      html  css  js  c++  java
  • singleton单例模式笔记

    单例模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点

    单例模式的要点有三个;一是某个类只能有一个实例;二是它必须自行创建这个实例;三是它必须自行向整个系统提供这个实例。

    Singleton模式主要作用是保证在Java应用程序中,一个类Class只有一个实例存在。
    一般Singleton模式通常有三种形式:
    第一种模式,是最常用的模式。是lazy initialization形式,也就是说第一次调用时初始Singleton,以后就不用再生成了。只需要初始化一次
    package spring.util.singleton;
    
    /**
     * @author fanbo
     *  单例模式一
     *  这是最常用的单例模式
     *  
     */
    public class FirstSingleton {
        
        private static FirstSingleton instance = null;
        
        private FirstSingleton(){}
    
        public static FirstSingleton getInstance() {
            if(instance==null){
                instance = new FirstSingleton();
            }
            return instance;
        }
        
        
    }

    第二种模式:

    package spring.util.singleton;
    
    /**
     * @author fanbo
     * 单例模式二
     * 在自己内部定义一个实例,供自己单独调用
     */
    public class SecondSingleton {
    
        //在自己内部定义自己的一个实例,只供内部调用
        private static SecondSingleton instance = new SecondSingleton();
        
        private SecondSingleton(){}
    
        //这里提供了一个供外部访问本class的静态方法,可以直接访问
        public static SecondSingleton getInstance() {
            return instance;
        }
        
        
    }

    第三种模式:

    package spring.util.singleton;
    
    /**
     * @author fanbo
     * 单例模式三   双重锁的形式
     */
    public class ThreeSingleton {
        
        private static ThreeSingleton instance = null;
        
        private ThreeSingleton(){}
    
        public static ThreeSingleton getInstance() {
            if(instance==null){
                synchronized (ThreeSingleton.class) {
                    if(null==instance){
                        instance = new ThreeSingleton();
                    }
                }
            }
            
            return instance;
        }
        
        
    
    }
    此笔记用来自我学习和分享知识,有不对的地方还请大家互相指教
  • 相关阅读:
    python 读取excel表格中的数据
    python 安装 pip 报错解决方案
    HDU-1150-MachineSchedule(二分图匹配)
    POJ-3177-RedundantPaths(边联通分量,缩点)
    POJ-3352-RoadConstruction(边双联通分量,缩点)
    F-三生三世
    D-温暖的签到题
    C-晾衣服
    A-坐飞机
    POJ-2777-CountColor(线段树,位运算)
  • 原文地址:https://www.cnblogs.com/willbesuccess/p/3449554.html
Copyright © 2011-2022 走看看