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

    public class Singleton {					//单例懒汉模式
    	private static Singleton instance = null;  //实例不能通过new获得,只能通过类方法获得,因此方法要加static
    											//静态方法只能访问静态属性,所以instance也用static修饰
    	private Singleton(){}      //构造方法设为private,外部类不能通过new实例化这个类
    	public static synchronized Singleton getInstance()  //定义一个获得实例的方法,外部类通过该方法获取单例类的实例,类方法加static
    	{													//synchronized是为了线程安全保证一次只能有一个线程访问
    		if(instance == null)
    		{
    			instance = new Singleton();
    		}
    		return instance;
    	}
    	
    }
    
    class SingletonTest{
    	public static void main(String[] args)
    	{
    		Singleton s1 = Singleton.getInstance();
    		Singleton s2 = Singleton.getInstance();
    		System.out.println(s1 == s2);
    	}
    }
    
    class Singleton2{    //饿汉方式
    	private static Singleton2 instance = new Singleton2();
    	private Singleton2(){}
    	public static Singleton2 getInstance()
    	{
    		return instance;
    	}
    }
    
  • 相关阅读:
    时间日期date/cal
    chown命令
    su命令
    which命令和bin目录
    python基础之文件操作
    python之模块之shutil模块
    python基础之面向对象01
    python基础之面向对象02
    python基础之map/reduce/filter/sorted
    python基础之模块之序列化
  • 原文地址:https://www.cnblogs.com/masterlibin/p/4781967.html
Copyright © 2011-2022 走看看