js里面的设计模式

  • 设计模式的目的:优化性能,利于维护。

一、工厂模式

  • 使用工厂模式,解决的是多次创建对象的问题,但是没有解决对象识别的问题(返回的都是同一个对象类型)
<script>
   //实例化不同的人
   function Factory(name,age,job){
       var obj = new Object();
       obj.name = name;
       obj.age = age;
       obj.job = job;
       obj.sleep = function () {
           console.log(this.name);
       }
       return obj;
   }
   var s1 = Factory('小赵',18,'学生');
   var s2 = Factory('小李',18,'学生');
   var s3 = Factory('小陈',18,'学生');
   console.log(s1, s2, s3);
</script>

在这里插入图片描述

二、构造函数模式

  • 没有显示创建对象,没有返回语句,直接给this指针上赋属性和方法。(eg:飞机大战)
    function Person(name,age,sex){
        this.name=name||"";
        this.age=age||"";
        this.sex=sex||"";
        this.sleep=function(){
            console.log("睡觉");
        }
        this.eat=function(){
            console.log("吃饭");
        }
    }
    var p=new Person('小赵',21,'女');
    console.log(p);
    p.sleep();
    p.eat(); 

在这里插入图片描述

三、原型模式

  • 使用原型对象来写代码。
  • 优点:
  • 1.给构造函数省略属性和方法,不考虑传递参数。
  • 2.原型对象上属性所有实例共享。
   function Person(){

   }
   Person.prototype = {
       constructor:Person,
       name:"小赵",
       age:"18",
       sleep:function(){
           console.log("睡觉");
       }
   }
   var p1 = new Person();
   //不共享的写下面
   p1.job = "打工";
   var p2 = new Person();
   p2.work = "开车";
   console.log(p1, p2);

在这里插入图片描述

四、构造函数模式+原型模式

    function Person(name,age){
        this.name=name||"";
        this.age=age||"";
    }
    Person.prototype={
        constructor:Person,
        sleep:function(){
            console.log("睡觉");
        }
    }
    var p=new Person('小赵',21);
    console.log(p);
    p.sleep(); 

在这里插入图片描述

五、单例模式(单子模式或单体模式)

  • 定义:产生一个类的实例
  • 核心:确保只有一个实例,提供全局访问。

1. 简单单例模式写法

    //产生唯一实例 返回单个对象
    //简单单例
    var sign=(function(){
        var instance;
        if(instance==undefined){
            instance=new Instance('小赵');
        }
        //构造函数代码
        function Instance(name){
            this.name=name;
        }
        Instance.prototype={
            sleep:function (){
                console.log(this.name+"睡觉");
            }
        }
        return instance;
    })()
    console.log(sign); 

在这里插入图片描述

2. 使用闭包写单例模式

方法1

    var instance=(function(){
        var ins;
        var instance=function(name){
            if(ins){
                return ins;
            }
            this.name=name;
            return ins=this;
        };
        instance.prototype={
            sleep:function(){
                console.log(this.name + "睡觉");
            }
        };
        return instance;
    })();
    var stu=new instance('小明');
    var stu1=new instance('小花');
    console.log(stu);
    console.log(stu1);
    console.log(stu == stu1);//true
    stu.sleep();
    stu1.sleep(); 

在这里插入图片描述

方法2

    var instance=(function(){
        function method(name){
            this.name=name;
        }
        method.prototype={
            sleep:function(){
                console.log(this.name + "睡觉");
            }
        };
        var ins;
        return function(name){
            if(ins){
                return ins;
            }
            ins=new method(name);
            return ins;
        }
    })();
    var stu=new instance('小明');
    var stu1=new instance('小花');
    console.log(stu == stu1);//true
    console.log(stu);
    console.log(stu1);
    stu.sleep();
    stu1.sleep(); 

在这里插入图片描述

六、观察者模式(观察和发布订阅模式)

  • 观察者模式定义的是一对多的关系的实际模式,让多个观察者同时观察监听同一个容器。
    //先建立一个观察者的操作类
    //存在以下功能,存储、添加、删除、通知、修改观察者
    var Subject={
        observer:[],//存储所有的观察者列表
        add:function(observe){
            //添加方法
            this.observer.push(observe);
        },
        remove:function(observer){
            //移除方法
            //找到匹配的人移除
            var index=this.observer.findIndex(function(item){
                return item===observer;
            });
            //删除这个人
            this.observer.splice(index,1);
            //通知这个人
            observer.update();
        },
        send:function(msg){
            //通知方法
            //通知当前每个update
            for(var index in this.observer){
                this.observer[index].update(msg);
            }
        }
    }
    //建立观察者对象
    //订阅页存在添加 修改 删除
    function Observer(name){
        this.name=name;
        this.subscrib={};//存储当前这个观察者的订阅
        this.update=function(msg){
            console.log(this.name + msg);
        };
        this.addsubscrib=function(key,fn){
            //添加订阅
            //检查订阅是否存在
            if(!this.subscrib[key]){
                this.subscrib[key]=[];
            }
            this.subscrib[key].push(fn);
        };
        this.publish=function(key){
            //发布 执行每个订阅
            for(var index in this.subscrib[key]){
                this.subscrib[key][index].call(this);//执行当前订阅函数
            }
        }
    }
    //实例化观察者
    var per1=new Observer('小赵');
    var per2=new Observer('小阮');
    per1.addsubscrib('object1',function(){
        console.log(this.name + "执行任务完成");
    });
    per1.addsubscrib('message',function(){
        console.log(this.name + "跳舞");
    });
    //执行任务
    per1.publish('object1');
    per1.publish('message');
    per2.addsubscrib('object2',function(){
        console.log(this.name + "执行任务完成");
    });
    per2.addsubscrib('message',function(){
        console.log(this.name + "跳舞");
    });
    //执行任务
    per2.publish('object2');
    per2.publish('message');
    console.log(per1, per2); 

在这里插入图片描述

  • dom操作中的发布-订阅模式
	//订阅
   document.body.addEventListener("click",handle);
   function handle(){
       console.log(1);
   }
   //移除
   document.body.removeEventListener("click",handle);
   //发布
   document.body.click();
  • 发布和订阅模式
   //订阅中心
   var pubsub = {
       list:{},//存储订阅事件
       //添加订阅方法
       subscribe:function(key,fn){
           if(!this.list[key])
           {
               this.list[key] = [];
           }
           this.list[key].push(fn);
       },
       //发布订阅
       publish:function(key,time){
           for(var index in this.list[key]){
               this.list[key][index].call(this);
           }
       },
       //取消订阅
       unpublish:function(key,fn){
           var that = this;
           if(!that.list[key])
               return;
           if(!fn)
           {
               console.log("fn参数不存在");
           }
           else
           {
               if(typeof fn == 'function')
               {
                   that.list[key].map(function(f,index){
                       if(f === fn)
                       {
                           that.list[key].splice(index,1);
                       }
                   });
               }
               else
               {
                   console.log("fn参数不是函数");
               }
           }
       }
   }
   //订阅
   pubsub.subscribe('gowork',function(time){
       console.log("上班了,打卡时间为:"+time);
   });
   pubsub.subscribe('backwork',work);
   function work(time){
       console.log("下班了,打卡时间为:"+time);
   }
   console.log(pubsub.list);
   //发布订阅
   pubsub.publish('gowork','8:00:00');
   pubsub.publish('backwork','18:00:00');
   //取消订阅
   pubsub.unpublish('backwork',work);
   console.log(pubsub.list);

在这里插入图片描述

七、策略模式

  • 原理:把算法和算法的使用分离开。
   //策略集合
   var leavl = {
       A:8,
       B:6,
       C:4,
       D:2,
       E:0
   }
   //策略使用
   var leavlScore = {
       base:60,
       A:function(){
           return this.base+leavl['A'];
       },
       B:function(){
           return this.base+leavl['B'];
       },
       C:function(){
           return this.base+leavl['C'];
       },
       D:function(){
           return this.base+leavl['D'];
       },
       E:function(){
           return this.base+leavl['E'];
       },
       checkLeavl:function(){
           var leavlS;
           if(this.base>=90)
           {
               leavlS = 'A';
           }
           else if(this.base>=80)
           {
               leavlS = 'B';
           }
           else if(this.base>=70)
           {
               leavlS = 'C';
           }
           else if(this.base>=60)
           {
               leavlS = 'D';
           }
           else
           {
               leavlS = 'E';
           }
           return this[leavlS]();
       }
   }
   //根据策略实现得分的情况
   function getScore(score){
       leavlScore.base = score;
       return leavlScore.checkLeavl();
   }
   console.log(getScore(90));//98
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
JavaScript 设计模式是在 JavaScript 编程中经常使用的一种代码组织和架构方法。设计模式可以帮助开发者解决常见的问题,并提供可复用的解决方案。 以下是一些常见的 JavaScript 设计模式: 1. 工厂模式(Factory Pattern):通过使用工厂方法创建对象,将对象的创建和使用分离开来,提高代码的可扩展性和可维护性。 2. 单例模式(Singleton Pattern):确保一个类只有一个实例,并提供一个全局访问点来访问该实例。 3. 观察者模式(Observer Pattern):定义了对象之间的一对多依赖关系,当一个对象的状态发生改变时,所有依赖它的对象都会被自动通知并更新。 4. 发布-订阅模式(Publish-Subscribe Pattern):也是一种观察者模式的变体,在这种模式中,发布者(Publisher)和订阅者(Subscriber)之间通过消息队列进行通信。 5. 原型模式(Prototype Pattern):通过复制现有对象来创建新对象,避免了使用类进行实例化的复杂性。 6. 适配器模式(Adapter Pattern):将一个类的接口转换成客户端所期望的另一个接口,使得原本不兼容的类可以一起工作。 7. 装饰者模式(Decorator Pattern):动态地给对象添加新的功能,而不影响其他对象。 8. 策略模式(Strategy Pattern):定义一系列算法,将每个算法封装起来,并使它们可以互换使用。 这些设计模式可以帮助开发者在编写 JavaScript 代码时更好地组织和设计代码结构,提高代码的可读性、可维护性和可扩展性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南初️

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值