外觀模式
- 該模式就是把一些複雜的流程封裝成一個接口提供給外部用戶更簡單的使用
- 門面角色:外觀模式的核心,它倍客戶角色調用,它熟悉子系統的共嗯那個,內部根據客戶角色的需求預
- 子系統角色:實現了子系統的功能,它對客戶角色和Facade是未知的
- 客戶角色:通過調用Facede來完成要實現的功能
class Sum{
sum(a,b){
return a+b;
}
}
class Minus{
minus(a,b){
return a-b;
}
}
class Multiply{
multiply(a,b){
return a*b;
}
}
class Divide{
divide(a,b){
return a/b;
}
}
class Calculator{
constructor(){
this.sumObj = new Sum();
this.minusObj = new Minus();
this.multiplyObj = new Multiply();
this.devideObj = new Divide();
}
sum(a,b){
return this.sumObj.sum(a,b);
}
minus(a,b){
return this.minusObj.minus(a,b);
}
multiply(a,b){
return this.multiplyObj.multiply(a,b);
}
divide(a,b){
return this.divideObj.divide(a,b);
}
}
let calculator = new Calculator();
console.log(calculator.sumObj.sum(1,2))
觀察者模式
- 被觀察者提供維護觀察者的一系列方法
- 觀察者提供更新接口
- 觀察者把自己註冊到被觀察者裏
- 在被觀察者發生變化的時候,調用觀察者的更新方法
class Star{
constructor(name){
this.name = name;
this.state = '';
this.observers = [];//觀察者
}
getState(){
return this.state;
}
setState(state){
this.state = state;
this.notifyAllObservers();
}
//增加一個新的觀察者
attach(observer){
this.observers.push(observer);
}
//通知所有的觀察者更新
notifyAllObservers(){
if(this.observers.length>0){
this.observers.forEach(observer=>observer.update());
}
}
}
class Fan{
constructor(name,star){
this.name = name;
this.star = star;
this.star.attach(this)
}
update(){
console.log(this.star.getState())
}
}
let star = new Star('Tiya');
let f1 = new Fan('zs',star)
star.setState('red')
promise.js
//監聽resovle執行then裏面傳的函數
class Promise{
constructor(fn){
this.successes = [];
let resolve = (data)=>{
this.successes.forEach(item=>item(data))
}
fn(resolve)
}
then(success){
this.successes.push(success);
}
}
let p = new Promise(function(resolve){
setTimeout(function(){
resolve("ok")
},2000)
})
p.then(()=>{
console.log('promise then')
})