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;
	}
}

 

posted @ 2015-09-04 16:55  32ddd  阅读(158)  评论(0编辑  收藏  举报