单例设计模式

单例设计模式

单例设计模式:所谓的单例设计模式,就是采取一定的方法保证在整个软件系统中,对某个类只能存在一个对象的实例
懒汉模式:

懒汉式:
坏处,加载时间过长。
好处:饿汉式是线程安全的。
饿汉式:好处:延迟对象的创建。
目前写法的坏处:线程不安全

这里改写成线程安全,加了同步代码块,同时使用volatile来保证可见性和禁止指令重排D。

class Singleton {
    private volatile static Singleton instance = null;

    private Singleton() {
    }

// DCL双检锁
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }


            }
        }
        return instance;
    }

}

public class SingletonTest {

    public static void main(String[] args) {
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println(instance1 == instance2);

    }

}
//懒汉设计模式
class Order {
    //1、私有化类的构造器
    private   Order() {

    }

    //先声明当前类的实例,没有初始化
    //此变量必须也为static的
    private volatile static Order instance=null;


    //
    public static Order instance() {
         if (instance == null) {
			synchronized(Order.class){
			if(instance==null){
             instance = new Order();
}

         }
         return instance;
    }
}

方式二:采用静态内部类的方式

/**
 * Created with IntelliJ IDEA.
 * @Author: pzx
 * @Date: 2022/05/23    18:50
 * @Version:1.0
 * 采用静态内部类来实现单例模式
 */
public class SingletonDemo {

    private SingletonDemo() {
    }

    /**
     * 通过静态内部类来帮帮我们创建一次,因为JVM只会加载一次这个类,从而保证了线程安全
     */
    private static class SingletonDemoHandler {
        private static SingletonDemo singleton = new SingletonDemo();
    }


    public SingletonDemo getInstance() {
        return SingletonDemoHandler.singleton;
    }


}

饿汉模式:

public class Singleton {
    public static void main(String[] args) {
        Bank b1 = Bank.getInstance();
        Bank b2 = Bank.getInstance();
        System.out.println(b2 == b1);

    }
}
//单例设计模式之饿汉式
class Bank {



    //1、私有化类的构造器
    private Bank() {

    }

    //    2、内部调用类的对象
    //4、要求此对象也为static的
    private static Bank instance = new Bank();

    //提供公共的静态的方法 ,返回类的对象
    public static  Bank getInstance() {
        return instance;
    }

}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值