Java设计模式-单例设计模式
作用:
为了保证在内存中只存在唯一的一个对象
实现方案:
- 要避免过多创建对象,应禁止通过构造函数创建对象;
- 由于外部不能创建对象,所以要在本类中创建该对象;
- 为了能够访问此对象,必须提供接口可以访问该对象。
代码实现:
- 饿汉式
public class Single {
private int data=10;
//第一步:使构造函数私有化
private Single(){}
//第二步:创建本类对象
private static Single single=new Single();
//第三步:提供静态方法获取对象
public static Single getInstance(){
return single;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
}
- 懒汉式
/*懒汉式*/
private Single(){}
private static Single single=null;
public static Single getInstance(){
if (single==null)
single=new Single();
return single;
}
- 优化懒汉式线程安全问题:
synchronized
,缺点:效率低,每次都需要判断加锁
/*懒汉式*/
private Single(){}
private static Single single=null;
public static synchronized Single getInstance(){
if (single==null)
single=new Single();
return single;
}
- 优化懒汉式效率问题,判断锁次数减少
/*懒汉式*/
private Single(){}
private static Single single=null;
public static Single getInstance(){
if (single==null){
synchronized(Single.class){
if (single==null){
single=new Single();
}
}
}
return single;
}
注:一般推荐使用饿汉式
测试代码:
class SingleDemo{
public static void main(String[] args) {
Single s1 = Single.getInstance();
Single s2 = Single.getInstance();
s1.setData(110);
System.out.println("s1的data值:"+s1.getData());
System.out.println("s2的data值:"+s2.getData());
}
}
运行结果:
s1的data值:110
s2的data值:110