Skip to content

Instantly share code, notes, and snippets.

@laispace
Created February 7, 2015 09:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laispace/3c22b798de1d2bbd1f0a to your computer and use it in GitHub Desktop.
Save laispace/3c22b798de1d2bbd1f0a to your computer and use it in GitHub Desktop.
设计模式-单例模式
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 (中国标准时间)
@laispace
Copy link
Author

laispace commented Feb 7, 2015

单例比起静态实例的优点是,我们需要时才会去创建它,无需浪费内存占用

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment