//状态模式
var status = {
statusArr:[],
on(state){
this.statusArr.push(state);
return this;
},
fire(){
this.statusArr.forEach((v,k)=>{
this.actionArr[v]();
})
},
actionArr:{
jump:function(){
console.log('jump');
},
run:function(){
console.log('run');
},
fire:function(){
console.log('fire');
},
}
}
status.on('run').on('jump').fire();
//观察者模式
//观察者模式
//抽奖 每转一圈,速度减慢
var obs = {
//监听队列
fallback:{
},
//注册监听
on:function(name,fn){
this.fallback[name] = fn;
},
//触发监听
fire:function(name){
this.fallback[name]();
},
//删除监听
delete:function(name){
this.fallback[name] = null
}
}
obs.on('done',()=>{
console.log('well done');
})
obs.fire('done')
//策略模式
function calc(type,a,b){
let calc = {
add:function(a,b){
return a+b;
},
declare:function(a,b){
return a-b;
}
}
return calc[type](a,b);
}
let res = calc('declare',3,5);
let res2 = calc('add',3,5);
console.log(res,res2);
//命令模式 只关心命令,不用关心别的
var cm = {
target:'dom1',
data:[{pic:'xxx.png',title:'xxx'}],
type:'left'
}
function command(){
var __html = '';
var create = function(styleObj,arr){
arr.forEach((v,k) => {
__html = ``;//拼接成显示的 html 字符串
});
}
var display = function(dom){
var dom = document.getElementById(dom);
dom.innerHtml = __html;
}
var excute = function(command){
var calcer = {
left:'float:left;',
top:''
}
create(calcer(command.type),command.data);
display(command.target);
}
return {
excute
}
}
command(cm);
//迭代器模式
let dector = function(){}
dector.has = (obj,value)=>{
let res = false;
for(let item in obj){
if(obj[item] === value){
res = true;
}
}
return res;
}
let s = dector.has({a:1},1)
console.log(s);
//惰性模式
let b = 100;
var a = (()=>{
if(b===100){
return a = ()=>{
console.log('a')
}
}else{
return a = ()=>{
console.log('b')
}
}
})()
a()