单例模式
function Fun(name,age){
this.name = name;
this.age = age;
}
Fun.prototype.f = function(){
console.log(‘见过你的美,还能爱上谁’);
}
const f1=new Fun(‘貂蝉’,18);
const f2=new Fun(‘貂蝉’,18);
console.log(f1==f2);
组合模式
class A{
constructor(){}
init(){
this.a1();
this.a2();
}
a1(){
console.log('我是a1');
}
a2(){
console.log('我是a2');
}
}
class B{
constructor(){}
init(){
this.b1();
this.b2();
this.b3();
}
b1(){
console.log('我是b1');
}
b2(){
console.log('我是b2');
}
b3(){
console.log('我是b3');
}
}
class C{
constructor(){}
init(){
this.c1();
this.c2();
this.c3();
this.c4();
}
c1(){ console.log('我是c1');}
c2(){ console.log('我是c2');} c
c3(){ console.log('我是c3');}
c4(){ console.log('我是c4');}
}
class Compose{
constructor(){
this.arr=[];
}
add(obj){
this.arr.push(obj);
}
execute(){
this.arr.forEach(function(item){
item.init();
});
}
}
const all=new Compose();
all.add(new A());
all.add(new B());
all.add(new C());
all.execute();
观察者模式
class Observer{
constructor(){
this.message=[];
}
on(type,fun){
if(this.message[type]){
this.message[type].push(fun);
}else{
this.message[type]=[fun];
}
};
emit(type, ...arr){
if(!this.message[type]){
return;
}
for(var i=0;i<=arr.length-1;i++){
for(var j=0;j<=this.message[type].length-1;j++){
if(arr[i]===this.message[type][j]){
arr[i]();
}
}
}
};
off(type,fun){
if(!this.message[type]){
return;
}
for(let i=0;i<=this.message[type].length-1;i++){
if(this.message[type][i]===fun){
this.message[type].splice(i,1);
i--;
}
}
};
}
const obj=new Observer();
obj.on('say',Hello);
obj.on('say',Hi);
obj.on('say',Hello);
obj.on('say',Who);
obj.on('say',Hello);
function Hello(){
console.log('你好,陌生人');
}
function Hi(){
console.log('嗨,很高兴见到你');
}
function Who(){
console.log('我想认识你');
}
obj.emit('say',Hello,Hi);
console.log(obj);
obj.on();