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;
    	}
    }
    
    
    多思考,多尝试。
  • 相关阅读:
    chkconfig命令
    Office 2010 与搜狗输入法兼容问题
    【转】WAS入门简介
    UTF8GB2312GBK
    System.getProperty
    Hibernate 事务方法保存clob类型数据
    Eclipse 或者 Myeclipse 提示选择工作空间设置
    request
    那些操蛋的人生
    Java新手入门很重要的几个基本概念
  • 原文地址:https://www.cnblogs.com/LynnMin/p/9449934.html
Copyright © 2011-2022 走看看