微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript 单例模式详解及简单实例

JS 单例模式

概要:

单例指一个类只有一个实例,这个类自行创建这个实例。

利用对象字面量直接生成一个单例:

rush:js;"> var singleton = { prop: 1,method: function(){ console.log(a); //1 } }

严格的说对象字面量可能不算单例模式,生成单例是对象字面量的作用(已经被封装),而单例模式是一个设计模式(需要自行构思或设计)。

在类内部用new生成实例的单例模式:

rush:js;"> var instance; var foo = function(){ if(!instance){ instance = new Singleton(); } return instance; function Singleton(){ this.name = 'single'; this.method = function(){ console.log(this.name); } }; }

var a = foo();
var b = foo();
a.method(); //single
console.log(a === b); //true

单例模式只要检测一个实例是否被生成。假如没有实例,则生成实例。假如已经生成则返回这个实例。保证这个类只有这一个实例。

由于hoisting,函数会提前声明,所以 singleton 函数放在哪都没所谓,但是每次调用都会声明函数singleton,可能会不够优雅。

由于new关键字是执行函数,同时this指向这个对象,所以可以判断类的this是否赋值给instance:

rush:js;"> var instance; var Singleton = function(){ if(instance){ return instance; } instance = this; this.name = 'single'; this.method = function(){ console.log(this.name); } }

var a = new Singleton();
var b = new Singleton();
a.method(); //single
console.log(a === b); //true

这个例子中,把instance指向了Singleton这个类,然后在类外部通过new来实例化,和上例中的new异曲同工。由于是通过修改this来达到检测是否执行过Singleton类,所以个人感觉不够语义化。

上面的例子用es6重构的写法。

类内部new生成单例:

rush:js;"> var instance; class foo{ static Singleton(){ if(!instance){ instance = new foo(); } return instance; } method(){ this.name = 'single'; console.log(this.name); } }

var a = foo.Singleton();
var b = foo.Singleton();
a.method(); //single
console.log(a === b); //true

修改this指向生成单例:

rush:js;"> var instance; class foo{ constructor(){ if(!instance){ this.Singleton(); } return instance; } Singleton(){ instance = this; this.name = 'single'; this.method = function(){ console.log(this.name); } } }

var a = new foo();
var b = new foo();
a.method(); //single
console.log(a === b); //true
  

当然除了这两种以外还有别的方式能实例化一个单例。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持

原文地址:https://www.jb51.cc/js/41686.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐