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;
    	}
    }
    
    
    多思考,多尝试。
  • 相关阅读:
    java-transaction事件
    Cookie,Session基础知识
    JSP基础笔记
    PHP----学生管理系统
    C语言程序设计-----贪吃蛇
    2019年数维杯三场征战赛
    回忆2018年高教杯数学建模大赛
    iPad横屏模式研究
    IOS UIWebView截获html并修改便签内容,宽度自适应
    如何保持iOS上键盘出现时输入框不被覆盖
  • 原文地址:https://www.cnblogs.com/LynnMin/p/9449934.html
Copyright © 2011-2022 走看看