Java设计模式-单例设计模式

Java设计模式-单例设计模式

作用:

为了保证在内存中只存在唯一的一个对象

实现方案:

  1. 要避免过多创建对象,应禁止通过构造函数创建对象;
  2. 由于外部不能创建对象,所以要在本类中创建该对象;
  3. 为了能够访问此对象,必须提供接口可以访问该对象。

代码实现:

  1. 饿汉式
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;
    }
}
  1. 懒汉式
    /*懒汉式*/
    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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值