单例设计模式
单例设计模式:所谓的单例设计模式,就是采取一定的方法保证在整个软件系统中,对某个类只能存在一个对象的实例
懒汉模式:
懒汉式:
坏处,加载时间过长。
好处:饿汉式是线程安全的。
饿汉式:好处:延迟对象的创建。
目前写法的坏处:线程不安全
这里改写成线程安全,加了同步代码块,同时使用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;
}
}