设计模式之创建型模式——单例模式

总体来说设计模式分为三大类:

创建型模式,共五种:工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式。

结构型模式,共七种:适配器模式、装饰器模式、代理模式、外观模式、桥接模式、组合模式、享元模式。

行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。

单例模式:

在Java应用中,单例对象能保证在一个JVM中,该对象只有一个实例存在。这样的模式有几个好处:

1、某些类创建比较频繁,对于一些大型的对象,这是一笔很大的系统开销。

2、省去了new操作符,降低了系统内存的使用频率,减轻GC压力。

3、有些类如交易所的核心交易引擎,控制着交易流程,如果该类可以创建多个的话,系统完全乱了。(比如一个军队出现了多个司令员同时指挥,肯定会乱成一团),所以只有使用单例模式,才能保证核心交易服务器独立控制整个流程。

单例模式实现方法:1、通过synchronized关键字锁方法。2、对过内部类维护单例。

代码如下:

//1、方法一:synchronized实现单例模式
public class SingletonPattern1 {
    //私有、静态实例,防止被引用。
    //此处赋值为null,目的为实现延迟加载
    private static SingletonPattern1 singletonPattern1 = null;
    
    //将构造方法私有化,防止被实例化
    private SingletonPattern1() {
    
    }
    
    //锁方法
    private static synchronized void initIntance() {
        if(singletonPattern1 != null) {
            singletonPattern1 = new SingletonPattern1();
        }
    }
    
    //外部调用方法:获取实例
    public static SingletonPattern1 getInstance() {
        if(singletonPattern1 == null) {
            initIntance();
        }
        return singletonPattern1;
    }
    
    //保证对象被序列化后,前后一致
        private Object readResolve() {
            return getInstance();
        }
    
}

//2.方法二:内部类实现单例模式
public class SingletonPattern2 {

    //构造方法私有化,防止被实例化
    private SingletonPattern2() {
        
    }
    
    //使用一个内部类维护单例
    private static class SingletonPattern2Factory{
        private static SingletonPattern2 singletonPattern2 = new SingletonPattern2();
    }
    
    //外部调用方法:获取实例
    public static SingletonPattern2 getInstance() {
        return SingletonPattern2Factory.singletonPattern2;
    }
    
    //保证对象被序列化后,前后一致
    private Object readResolve() {
        return getInstance();
    }
    
    
}

PS:该文参考:https://blog.csdn.net/tyyking/article/details/52300771

猜你喜欢

转载自blog.csdn.net/qq_41306795/article/details/81173779