学习设计模式(一):单例模式

版权声明:个人博客:https://blog.csdn.net/qq_22754377 转载请注明出处 https://blog.csdn.net/qq_22754377/article/details/82108052

1.什么是设计模式

设计模式,维基百科中的定义是:设计模式(design pattern)是对软件设计中普遍存在(反复出现)的各种问题,所提出的解决方案。设计模式在Java开发中得到了广泛的应用,设计模式的类别有23种左右,今天先给大家介绍一下单例模式。

2.单例模式介绍与设计思路

实现单例模式的思路是:一个类能返回对象一个引用(永远是同一个)和一个获得该实例的方法(必须是静态方法,通常使用getInstance这个名称);当我们调用这个方法时,如果类持有的引用不为空就返回这个引用,如果类保持的引用为空就创建该类的实例并将实例的引用赋予该类保持的引用;同时我们还将该类的构造函数定义为私有方法,这样其他处的代码就无法通过调用该类的构造函数来实例化该类的对象,只有通过该类提供的静态方法来得到该类的唯一实例。

3.单例模式的代码实现

1.饿汉式

/**
 * @program: DesignPatterns
 * @description: 单例模式-饿汉式
 * @author: Mr.Wang
 * @create: 2018-08-25
 **/
public class Singleton {
    //new一个对象,是唯一的对象
    private static Singleton single = new Singleton();
    //构造函数private,在其他类中无法调用,所以不能new对象,保证只有一个对象
    private Singleton(){
        System.out.println("lazy singleton");
    };
    //供其他接口访问的,得到该对象的方法
    public static Singleton getSingle() {
        return single;
    }
}

2.懒汉式

/**
 * @program: DesignPatterns
 * @description: 懒汉式线程安全,同时保证加载延迟
 * @author: Mr.Wang
 * @create: 2018-08-25
 **/
public class SingletonMuliThread {
    private static SingletonMuliThread singletonMuliThread;
    private SingletonMuliThread(){}

    public static synchronized SingletonMuliThread getSingletonMuliThread() {
        if(singletonMuliThread==null){
             singletonMuliThread = new SingletonMuliThread();
        }
        return singletonMuliThread;
    }
}

3.DCL双重校验锁

/**
 * @program: DesignPatterns
 * @description: 双重校验锁,既保证线程安全,又保证效率
 * @author: Mr.Wang
 * @create: 2018-08-25
 **/
public class SingletonDCL {
    private static SingletonDCL singletonDCL;
    private SingletonDCL(){}

    public static SingletonDCL getSingletonDCL() {
        //第一次判断为了确定是否是null,如果是null加锁后在判断一次是为了避免在这过程中有另外一个线程已经new了对象
        //因为当new完第一个对象后,以后的第一个if就不会进去了,所以加锁也就不会进行了,加锁只会出现在第一次new的时候
        if(singletonDCL==null){
            synchronized (SingletonDCL.class){
                if(singletonDCL==null){
                    singletonDCL = new SingletonDCL();
                }
            }
        }
        return singletonDCL;
    }
}

4.枚举法

/**
 * @program: DesignPatterns
 * @description: 单例枚举方式
 * @author: Mr.Wang
 * @create: 2018-08-25
 **/
public enum SingletonEnum {
    //单例
    INSTANCE;
    public void print(){
        System.out.println("enum singleton");
    }
}

源码地址:https://github.com/wangtengke/DesignPatterns
个人博客:https://blog.csdn.net/qq_22754377

猜你喜欢

转载自blog.csdn.net/qq_22754377/article/details/82108052