class Singleton { constructor() { this.conn = this.connect(); } static getInstance() { if (!Singleton.instance) { Singleton.instance = new Singleton(); } return Singleton.instance; } connect() { console.log('连接数据库'); return { conn: "这是一个数据库句柄" }; } find() { console.log('查询数据库'); }}let singleton1 = Singleton.getInstance();let singleton2 = Singleton.getInstance();console.log("singleton1", singleton1, "singleton2", singleton2)console.log(singleton1 === singleton2)
连接数据库singleton1 => Singleton { conn: { conn: '这是一个数据库句柄' } } | singleton2 => Singleton { conn: { conn: '这是一个数据库句柄' } }比较结果: true