当前位置: 面试刷题>> 单例模式 (经典算法题500道)


题目描述补充

题目:实现单例模式

单例模式(Singleton Pattern)是一种常用的软件设计模式,它的目的是确保一个类仅有一个实例,并提供一个全局访问点来获取这个实例。在多种场景下,如配置文件的读取、数据库连接池、线程池等,单例模式都能发挥重要作用。

请分别使用PHP、Python和JavaScript语言实现单例模式,并确保实例的唯一性。

PHP 示例代码

class Singleton
{
    // 私有静态变量,存储唯一实例
    private static $instance = null;

    // 私有构造函数,防止外部实例化
    private function __construct()
    {
    }

    // 私有克隆方法,防止外部克隆
    private function __clone()
    {
    }

    // 私有反序列化方法,防止外部反序列化
    private function __wakeup()
    {
    }

    // 静态方法,用于获取唯一实例
    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
}

// 使用示例
$instance1 = Singleton::getInstance();
$instance2 = Singleton::getInstance();

// 验证实例是否唯一
var_dump($instance1 === $instance2); // 输出: bool(true)

Python 示例代码

class Singleton:
    # 私有静态变量,存储唯一实例
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(Singleton, cls).__new__(cls)
        return cls._instance

# 使用示例
instance1 = Singleton()
instance2 = Singleton()

# 验证实例是否唯一
print(instance1 is instance2)  # 输出: True

JavaScript 示例代码

class Singleton {
    // 静态私有字段(使用WeakMap模拟,因为ES2020之前JS没有真正的私有静态字段)
    static instances = new WeakMap();

    constructor() {
        if (Singleton.instances.has(Singleton)) {
            return Singleton.instances.get(Singleton);
        }
        Singleton.instances.set(Singleton, this);

        // 初始化代码
        // ...
    }

    // 获取实例
    static getInstance() {
        if (!Singleton.instances.has(Singleton)) {
            new Singleton(); // 触发构造函数
        }
        return Singleton.instances.get(Singleton);
    }
}

// 使用示例
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();

// 验证实例是否唯一
console.log(instance1 === instance2); // 输出: true

码小课网站中有更多关于设计模式、算法及编程技巧的相关内容分享,欢迎大家前往学习交流。

推荐面试题