设计模式(一)之单例模式

设计模式(一)之单例模式

单例模式是java中最简单的设计模式

单例模式保证一个类仅有一个实例,并提供一个访问它的全局访问点。

特点:

  1. 单例类只能有一个实例

  2. 单例类必须自己创建自己的唯一实例

  3. 单例类必须给所有其他对象提供这一实例

意图:保证一个类仅有一个实例,并提供一个访问它的全局访问点。

主要解决:一个全局使用的类频繁地创建与销毁。

何时使用:当您想控制实例数目,节省系统资源的时候。

如何解决:判断系统是否已经有这个单例,如果有则返回,如果没有则创建。

关键代码:构造函数是私有的。
应用场景: 1.一些设备管理器常常设计为单例模式,比如一个电脑有两台打印机,在输出的时候就要处理不能两台打印机打印同一个文件。
2.创建的一个对象需要消耗的资源过多,比如 I/O 与数据库的连接等。
3.Web应用的配置对象的读取,一般也应用单例模式,这个是由于配置文件是共享的资源。
UML图:

这里写图片描述

说是简单可能是牵扯到一个类吧

这里介绍四种单例:

上代码:

1.饿汉式

/**
 * 饿汉式单例类
 * 单例类被加载时就将自己实例化
 * 是在不管你用的用不上,一开始就建立这个单例对象
 *  优点:没有加锁,执行效率会提高。
    缺点:类加载时就初始化,浪费内存。
 */
public class EagerSingleton {
    private static EagerSingleton instance = new EagerSingleton();
    private EagerSingleton(){}
    public static EagerSingleton getInstance(){
        System.out.println(instance);
        return instance;
    }
}

2.懒汉式

/**
 * 懒汉式单例类
 * 延时加载 在第一次被引用时才将自己实例化(可以说是贼懒)
 * 必须加锁 synchronized 才能保证单例
 *  优点:第一次调用才初始化,避免内存浪费。
    缺点:必须加锁 synchronized 才能保证单例,但加锁会影响效率。
 */
public class LazySingleton {

    private static LazySingleton instance;//这时的instance为null

    public LazySingleton() { }

//    //不支持多线程。因为没有加锁 synchronized
//    public static LazySingleton getInstance() {
//        if (instance==null){
//            instance = new LazySingleton();
//            System.out.println(instance);
//        }
//        return instance;
//    }

    //支持多线程
    //但是有一个问题 线程在每次调用getInstanceWithSynchronized()的时候都要加锁 影响效率 此时就需要双重校验锁了
    public static synchronized LazySingleton getInstanceWithSynchronized(){
        if (instance == null){
            instance = new LazySingleton();
        }
        System.out.println(instance);
        return instance;
    }
}

3.双重校验锁

/**
 * 双重校验锁
 * DCL,即 double-checked locking
 * JDK 版本:JDK1.5 起
    是否 Lazy 初始化:是
    是否多线程安全:是
 */
public class DCLSingleton {

    private volatile static DCLSingleton instance;

    private DCLSingleton() { }

    /**
     * 该方法为什么要判断两次是否为null
     * 这就考虑多线程了
     * 当instance为null的时候 可能两个线程都调用getInstance() 然后都满足第一个判断条件
     * 由于synchronized加锁 这个时候有一个线程进入 另一个线程处于等待状态
     * 第一个线程满足第二个判断条件 并创建了实例 此时释放资源 打开锁
     * 第二个线程加锁 进入第二个判断条件 发现实例已经创建 不满足第二个判断条件,原因是instance有volatile修饰
     * volatile确保instance被初始化DCLSingleton实例时 多个线程能正确处理instance变量
     * @return
     */
    public static DCLSingleton getInstance() {
        if (instance == null){
            synchronized (DCLSingleton.class){
                if (instance == null){
                    instance = new DCLSingleton();
                }
            }
        }
        System.out.println(instance);
        return instance;
    }
}

4.静态内部类 登记式单例类

/**
 * 登记式单例类 静态内部类
 * 是否 Lazy 初始化:是
 * 是否多线程安全:是
 */
public class StaticInnerSingleton {
    private static class SingletonHolder{
        private static final StaticInnerSingleton INSTANCE = new StaticInnerSingleton();
    }

    private StaticInnerSingleton() { }
    public static final StaticInnerSingleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}

测试类如下:

public class SingletonTest {

    public static void main(String[] args) {
        //恶汉式单例类
        EagerSingleton eagerSingleton = EagerSingleton.getInstance();
        EagerSingleton eagerSingleton2 = EagerSingleton.getInstance();

        //调用懒汉式单例类
//        LazySingleton lazySingleton = LazySingleton.getInstance();
        //支持多线程的懒汉式单例类 打印的是同一个实例 因为单例模式模式就创建一个实例
        LazySingleton lazySingletonSynchronized = LazySingleton.getInstanceWithSynchronized();
        LazySingleton lazySingletonSynchronized2 = LazySingleton.getInstanceWithSynchronized();
        // 双重校验锁
        DCLSingleton dclSingleton = DCLSingleton.getInstance();
        DCLSingleton dclSingleton2 = DCLSingleton.getInstance();
        //静态内部类
        StaticInnerSingleton staticInnerSingleton = StaticInnerSingleton.getInstance();
        StaticInnerSingleton staticInnerSingleton2 = StaticInnerSingleton.getInstance();
        boolean equals = staticInnerSingleton.equals(staticInnerSingleton2);
        System.out.println(equals);
    }
}

控制台打印:
这里写图片描述

总结:

一般采用饿汉式,若对资源十分在意可以采用静态内部类,不建议采用懒汉式及双重检测

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值