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

    定义 确保一个类只有一个实例,并提供一个全局访问点。
    延迟实例化

    public class Singleton {
    	private static Singleton instance;
    
    	private Singleton() { //构造函数私有化;
    	};
    
    	public static Singleton getInstatnce() { //全局访问点;
    		if (instance == null) {
    			instance = new Singleton();
    		}
    		return instance;
    	}
    }
    
    

    注意对于多线程可能存在同时创建出多个实例出来,
    延迟实例化的改进

    
    public class Singleton {
    	private static Singleton instance;
    
    	private Singleton() { //构造函数私有化;
    	};
    
    
    //加入synchronized进行同步,但是性能会下降;
    	public static synchronized Singleton getInstatnce() { //全局访问点;
    		if (instance == null) {
    			instance = new Singleton();
    		}
    		return instance;
    	}
    }
    
    

    不延迟

    //JVM加载这个类的时候就创建实例;
    public class Singleton {
    	private static Singleton instance =  new Singleton();
    
    	private Singleton() { //构造函数私有化;
    	};
    
    	public static synchronized Singleton getInstatnce() { //全局访问点;
    	
    		return instance;
    	}
    }
    
    

    双重检查加锁

    
    public class Singleton {
    	private volatile static Singleton instance ;
    
    	private Singleton() { //构造函数私有化;
    	};
    
    	public static  Singleton getInstatnce() { //全局访问点;
    	
    		if(instance==null) {
    			synchronized(Singleton.class){ //实例化的时候才加锁;
    				instance = new Singleton();
    			}
    		}
    		return instance;
    	}
    }
    
    
    多思考,多尝试。
  • 相关阅读:
    C++ 类 析构函数
    Oracle 11g rac 添加新节点测试
    rac添加新节点的步骤与方法
    X 传输表空间方法留待整理
    1913: 成绩评估
    1066: 输入n个数和输出调整后的n个数
    1005: 渊子赛马
    Problem Y: 哪一天,哪一秒?
    Problem T: 结构体学生信息排序
    Problem O: 国家排序
  • 原文地址:https://www.cnblogs.com/LynnMin/p/9449934.html
Copyright © 2011-2022 走看看