首页 > 编程语言 > 详细

java单例

时间:2015-09-04 18:14:41      阅读:252      评论:0      收藏:0      [点我收藏+]
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;
	}
}

 

java单例

原文:http://www.cnblogs.com/masterlibin/p/4781967.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!