前端设计模式

// 实现单例设计模式 利用闭包 缓存实例对象 只产生一个实例

let single=(function(){

    let singleObj=null;

    function getInstance(){

        if(!singleObj){

            singleObj=new dialogObj();

        }

        return singleObj

    }

    function dialogObj(){

        this.name='yang'

    }

    return getInstance

})()

single().name='zhang';//修改的是一个实例

console.log(single())//还是修改之后的这个实例dialogObj {name: 'zhang'}



//工厂模式  根据传入条件参数不同生成不同的实例对象理解成 生产不同的商品

function WlCar(props){

    this.color=props;

    this.name='五菱宏光';

}

function DzCar(props){

    this.color=props;

    this.name='一汽大众';

}

function carFactory(){

    this.create=function(type,props){

        if(type=='wl'){

            return new WlCar(props)

        }else if(type=='dz'){

           return  new DzCar(props)

        }

    }

}

let carName=[];

let creatCar=new carFactory();

carName.push(creatCar.create('wl','red'));

carName.push(creatCar.create('dz','white'));

console.log(carName);/* 0: WlCar {color: 'red', name: '五菱宏光'}

1: DzCar {color: 'white', name: '一汽大众'} */

//观察者模式:观察者模式又称发布订阅模式(Publish/Subscribe Pattern)
/* 
观察者模式的思想用一句话描述就是:被观察对象(subject)维护一组观察者(observer),当被观察对象状态改变时,通过调用观察者的某个方法将这些变化通知到观察者。
比如给DOM元素绑定事件的 addEventListener() 方法:

target.addEventListener(type, listener [, options]);
*/
class Subject{
    constructor(){
        this.observe=[]
    }
    add(observe){
        this.observe.push(observe)
    }
    remove(ob){
        this.observe=this.observe.filter(v=>v!=ob);
    }
    notice(){
        this.observe.forEach((val)=>{
            val.call();
        })
    }
}
let sub=new Subject();
function f1(){
    console.log('我是被订阅的f1')
}
function f2(){
    console.log('我是被订阅的f2')
}
sub.add(f1);//接收观察者 使其订阅自己
sub.add(f2);//接收观察者 使其订阅自己
sub.notice();//事件触发 通知观察者
sub.remove(f2);//接收观察者 取消订阅自己
sub.notice();//事件触发 通知观察者

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值