// 实现单例设计模式 利用闭包 缓存实例对象 只产生一个实例
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();//事件触发 通知观察者
前端设计模式
于 2022-01-23 23:29:22 首次发布