Created
February 7, 2015 09:44
-
-
Save laispace/3c22b798de1d2bbd1f0a to your computer and use it in GitHub Desktop.
设计模式-单例模式
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var singleton = (function () { | |
function Singleton(opts) { | |
this.createdAt = opts.createdAt || new Date(); | |
} | |
var _instance; | |
var static = { | |
name: 'singleton', | |
getInstance: function (opts) { | |
if (!_instance) { | |
_instance = new Singleton(opts) | |
} | |
return _instance; | |
} | |
} | |
return static; | |
})(); | |
// first time we init this singleton | |
var date1 = new Date(); | |
singleton.getInstance({createdAt: date}); | |
console.log(singleton.getInstance().createdAt); //=> Sat Feb 07 2015 17:41:21 GMT+0800 (中国标准时间) | |
// next time we just return this singleton | |
var date2 = new Date(); | |
singleton.getInstance({createdAt: date2}); | |
console.log(singleton.getInstance().createdAt); //=> //=> Sat Feb 07 2015 17:41:21 GMT+0800 (中国标准时间) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
单例比起静态实例的优点是,我们需要时才会去创建它,无需浪费内存占用