前端设计模式(一):单例模式

打印 上一主题 下一主题

主题 1812|帖子 1812|积分 5436

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
​                单例模式就是保证类的实例只有一个,这就是它的作用,比如在前端中,创建全局唯一的对话框实例,记录日志信息全局唯一实例等等。
单例模式在前端的两种实现方式:

1.通过原型方法实现
  1. const Singleton = function () {
  2.     this.instance = null;
  3. };
  4. Singleton.getInstance = function (name) {
  5.     if (!this.instance) {
  6.         this.instance = new Singleton();
  7.     }
  8.     return this.instance;
  9. };
  10. const a = Singleton.getInstance();
  11. const b = Singleton.getInstance();
  12. console.log(a === b); // true
复制代码
2.通过静态方法实现
  1. class SingleDog {
  2.   static instance;
  3.   show() {
  4.     console.log('我是一个单例对象')
  5.   }
  6.   static getInstance() {
  7.     // 判断是否已经new过1个实例
  8.     if (!SingleDog.instance) {
  9.       // 若这个唯一的实例不存在,那么先创建它
  10.       SingleDog.instance = new SingleDog()
  11.     }
  12.     // 如果这个唯一的实例已经存在,则直接返回
  13.     return SingleDog.instance
  14.   }
  15. }
  16. const s3 = SingleDog.getInstance()
  17. const s4 = SingleDog.getInstance()
  18. console.log(s3 === s4); // true
复制代码
实际上,上面两种方法模仿的是Java语言中的单例实现方式,平常我们前端开发,基于ES6使用模块导入导出,也可以看作单例模式:
  1. // 比如这是SingletonExample.js
  2. // 可以定义一些属性,方法等等,然后通过export导出,其他模块再分别导入
  3. const array_state = [];
  4. const methodTest = function() {
  5.     console.log('这是测试方法')
  6. }
  7. export default {
  8.     array_state, methodTest
  9. }
复制代码
单例模式的应用场景:

1.利用单例模式思想 来实现 登录框的 显示和隐藏
  1. class LoginForm {
  2.     constructor(){
  3.         this.state = 'hide'
  4.     }
  5.    
  6.     show(){
  7.         if(this.state === 'show'){
  8.             console.log('已经显示');
  9.             return
  10.         }
  11.         this.state = 'show';
  12.         console.log('登录框已显示')
  13.     }
  14.    
  15.     hide(){
  16.         if(this.state === 'hide'){
  17.             console.log('已经隐藏');
  18.             return
  19.         }
  20.         this.state = 'hide';
  21.         console.log('登录框已隐藏')
  22.     }
  23. }
  24. LoginForm.getInstance = (function(){
  25.     let instance
  26.     return function() {
  27.         if(!instance){
  28.             instance = new LoginForm();
  29.         }
  30.         return instance
  31.     }
  32. })
复制代码
测试:
  1. let login1 = LoginForm.getInstance();
  2. login1.show(); //打印:登录框显示成功
  3. let login2 = LoginForm.getInstance();
  4. login2.hide(); //打印:登录框隐藏成功
  5. console.log(login1 === login2)
复制代码
其他的应用场景例如,vuex,redux中的store都是单例模式实现的
关于单例模式的思考:

​                其实,在前端使用Vue,React等框架开发时,很难再去使用传统的单例模式,因为ES6的导入导出不仅写法优雅,而且编码使用都比传统的书写方式方便。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

万万哇

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表