单例模式:
多次实例化,只会执行构造函数一次,提高性能
在一个类只能有一个实例,即使多次实例化该类,也只返回第一次实例化后的实例对象
单例模式能减少不必要的内存开销,并且在减少全局的函数和变量冲突也具有重要的意义。
class Db { static getInstance() { //单例 if (!Db.instance) { Db.instance = new Db(); } return Db.instance; } constructor() { console.log('constructor,实例化触发构造函数'); this.connect(); } connect() { console.log('连接数据库'); } find() { console.log('查询数据库'); } } var myDb1 = Db.getInstance(); var myDb2 = Db.getInstance(); var myDb3 = Db.getInstance(); var myDb4 = Db.getInstance(); myDb1.find(); myDb2.find(); myDb3.find(); myDb4.find(); /** * constructor,实例化触发构造函数 * 连接数据库 * 查询数据库 * 查询数据库 * 查询数据库 * 查询数据库 */