zoukankan      html  css  js  c++  java
  • Java的单例模式(singleton)

    为什么需要单例?只因为国家的独生子女政策(当然现在可以生2个)

    单例是一个很孤独的物种,因为它的类里面做多只有也仅只有它一个。

    常见的是懒汉及饿汉模式,

    1.懒汉,为什么这么叫,看看英文,原为lazy loading,lazy(懒惰的),laoding(音如同佬),叫懒佬,然后一个佬==一条汉子,为好听,故懒汉。

    最基础的懒汉模式:

    //单例模式
    public class Singleton {
    	
    	// 私有化构造方法,使得外部不可能有由new产生实例;
    	private Singleton() {
    	}
    
    	// 懒汉模式
    	private static Singleton instance = null;
    	//不加synchronized,线程有问题;
    	public static Singleton getInstance() {
    		if (instance == null)
    		instance = new Singleton();
    		return instance;
    	}
    
    }
    

     上面有线程安全的问题,如果多线程情况下,可以得出多个实例。

    加入synchronized 改进后:

    //单例模式
    public class Singleton {
        
        // 私有化构造方法,使得外部不可能由用new产生实例;
        private Singleton() {
        }
    
        // 懒汉模式
        private static Singleton instance = null;
        //不加synchronized,线程有问题;
        public static synchronized Singleton getInstance() {
            if (instance == null)
            instance = new Singleton();
            return instance;
        }
    
    }

    懒,因为用到了才加载。

    饿汉,汉就不解释,上面有。为什么叫饿?因为不管你有没使用这个单例,它都会实例化,在内存中,好像一个很饥饿的人,不管什么,先吃了再说。

    具体如下:

    //饿汉模式
    public class Singleton2 {
    	//私有化构造方法,使得外表不能用new产生一个实例。
    	private Singleton2(){}
    	//饿汉模式,不管你有没用这个实例,先实例化。
    	private static Singleton2 instance =new Singleton2();
    	public static Singleton2 getInstance(){
    		return instance;
    	};
    
    }
    
  • 相关阅读:
    如何判断PHP 是ts还是nts版的
    让IE支持placeholder属性
    解决点击浏览器后退按钮页面过期的问题
    git记住用户名密码
    php保存base64数据
    azure注册码
    SQL Server 2008 R2密钥序列号
    SQL允许远程访问
    PHP生成表格
    PHP发起get post put delete请求
  • 原文地址:https://www.cnblogs.com/idignew/p/7409887.html
Copyright © 2011-2022 走看看