「软件工程-设计模式」 单例模式

Posted by Dawn-K's Blog on February 22, 2021

单例模式

概述

单例模式是说处于某种原因, 我们只能初始化一个对象, 然后在程序中都是引用这对象, 而不能创建新对象.

实现

线程不安全的懒汉式

首要的条件是将构造函数设置为私有, 然后当且仅当 getInstance 被调用且还未曾初始化过对象的时候, 才创建一个对象. 这个实现方法简单, 但是线程不安全, 也就是如果有两个线程紧跟着调用了if那一句的话, 就会产生两个对象.

1
2
3
4
5
6
7
8
9
10
11
public class Singleton {  
    private static Singleton instance;  
    private Singleton (){}  
  
    public static Singleton getInstance() {  
    if (instance == null) {  
        instance = new Singleton();  
    }  
    return instance;  
    }  
}

线程安全的懒汉式

getInstance 加一个同步锁. 虽然实现了线程安全, 但是影响了效率. (以后的方法都是线程安全的)

1
2
3
4
5
6
7
8
9
10
public class Singleton {  
    private static Singleton instance;  
    private Singleton (){}  
    public static synchronized Singleton getInstance() {  
    if (instance == null) {  
        instance = new Singleton();  
    }  
    return instance;  
    }  
}

饿汉式

这种解决方案也比较粗暴, 就是在类初始化的时候就创建对象, 这样会浪费内存, 产生无用的垃圾对象.

1
2
3
4
5
6
7
public class Singleton {  
    private static Singleton instance = new Singleton();  
    private Singleton (){}  
    public static Singleton getInstance() {  
    return instance;  
    }  
}

双重校验锁(DCL)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Singleton {  
    private volatile static Singleton singleton;  
    private Singleton (){}  
    public static Singleton getSingleton() {  
        if (singleton == null) {  
            synchronized (Singleton.class) {  
                if (singleton == null) {  
                    singleton = new Singleton();  
                }  
            }  
        }  
        return singleton;  
    }  
}

此外还有 登记式/静态内部类 和 枚举方法, 日后在探究.