限制類的實例化次數只能是一次。node
若是該實例不存在的狀況下,能夠經過一個方法建立一個類來實現建立類的新實例,若是實例已經存在,它會簡單返回該對象的引用。mongodb
經過打印privateRandomNumber來驗證是否爲同一個實例數據庫
let mySingleton = (()=> { let instance; let init = ()=> { let privateMethod = ()=> {//私有方法 console.log('I am privateMethod'); } let privateVariable = 'I am also private'; let privateRandomNumber = Math.random(); return {//共有方法和變量 publicMethod: ()=> { console.log('I am public'); }, publicProperty: 'I am also public', getRandomNumber: ()=> { return privateRandomNumber; } } } return {//獲取Singleton的實例,若是存在就返回,不存在就建立新實例 getInstance: ()=> { if(!instance) { instance = init(); } return instance; } } })(); let singleA = mySingleton.getInstance(); let singleB = mySingleton.getInstance(); console.log(singleA.getRandomNumber() === singleB.getRandomNumber());//ture
簡單封裝node鏈接mongodb數據庫json
const MongoDB = require('mongodb') const MongoClient = require('mongodb').MongoClient const ObjectID = MongoDB.ObjectID const Config = require('./config') class Db { static getInstance() { if(!Db.instance) { Db.instance = new Db() } return Db.instance } constructor() { this.dbClient = '' this.connect() } connect() {//鏈接數據庫 let that = this return new Promise((resolve, reject)=> { if(!that.dbClient) { MongoClient.connect(Config.dbUrl, {useNewUrlParser:true}, (err, client)=> { if(err) { reject(err) }else { that.dbClient = client.db(Config.dbName) resolve(that.dbClient) } }) }else { resolve(that.dbClient) } }) } find(collectionName, json) { return new Promise((resolve, reject)=> { this.connect().then((db)=> { let result = db.collection(collectionName).find(json) result.toArray((err, docs)=> { if(err) { reject(err) return } resolve(docs) }) }) }) } update(collectionName, json1, json2) { return new Promise((resolve, reject)=> { this.connect().then((db)=> { db.collection(collectionName).updateOne(json1, { $set: json2 },(err, result)=> { if(err) { reject(err) }else { resolve(result) } }) }) }) } insert(collectionName, json) { return new Promise((resolve, reject)=> { this.connect().then((db)=> { db.collection(collectionName).insertOne(json, (err, result)=> { if(err) { reject(err) }else { resolve(result) } }) }) }) } remove(collectionName, json) { return new Promise((resolve, reject)=> { this.connect().then((db)=> { db.collection(collectionName).removeOne(json, (err, result)=> { if(err) { reject(err) }else { resolve(result) } }) }) }) } getObjectId(id) { return new ObjectID(id) } } module.exports = Db.getInstance()
《Javascript設計模式》segmentfault
JS設計模式之Obeserver(觀察者)模式、Publish/Subscribe(發佈/訂閱)模式
JS設計模式之Factory(工廠)模式
JS設計模式之Singleton(單例)模式
JS設計模式之Facade(外觀)模式
JS設計模式之Module(模塊)模式、Revealing Module(揭示模塊)模式設計模式