Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

设计模式 #43

Open
ChelesteWang opened this issue Mar 6, 2022 · 3 comments
Open

设计模式 #43

ChelesteWang opened this issue Mar 6, 2022 · 3 comments

Comments

@ChelesteWang
Copy link
Owner

ChelesteWang commented Mar 6, 2022

策略模式--简化 if else
原理策略对象搭配对象访问

let object = {
    ADD:(a,b)=>a+b,
    SUB:(a,b)=>a-b,
    MUL:(a,b)=>a*b,
    DIV:(a,b)=>a/b,
    MOD:(a,b)=>a%b,
    POW:(a,b)=>a**b,
    SQRT:(a)=>Math.sqrt(a),
    ABS:(a)=>Math.abs(a),
};

function compute(a,b,operator){
    return object[operator](a,b);
}
@ChelesteWang
Copy link
Owner Author

单例模式--全局唯一对象
如果没有则创建如果有就返回

function createObj(createMethod) {
  let obj;
  return function () {
    return obj || (obj = createMethod.call(this, arguments));
  };
}

let obj = createObj(function () {
  return {
    name: "obj",
    message: "created by createObj",
  };
});

@ChelesteWang
Copy link
Owner Author

ChelesteWang commented Mar 6, 2022

适配器模式 -- 用于转换接口

function A() {
  return {
    A: function () {
      return "A";
    },
  };
}

function B() {
  return {
    B: function () {
      return "B";
    },
  };
}

function C() {
  return {
    C: function () {
      return "C";
    },
  };
}

function Word(word) {
  return function () {
    return {
      word: function () {
        switch (word) {
          case "A":
            return A().A();
          case "B":
            return B().B();
          case "C":
            return C().C();
        }
      },
    };
  };
}

@ChelesteWang
Copy link
Owner Author

发布订阅模式

class Event {
    events = {};
  
    emit(type, ...args) {
      const listeners = this.events[type];
      for (const listener of listeners) {
        listener(...args);
      }
    }
  
    on(type, listener) {
      this.events[type] = this.events[type] || [];
      this.events[type].push(listener);
    }
  
    once(type, listener) {
      const callback = (...args) => {
        this.off(type, callback);
        listener(...args);
      };
      this.on(type, callback);
    }
  
    off(type, listener) {
      this.events[type] = this.events[type] || [];
      this.events[type] = this.events[type].filter(
        (callback) => callback !== listener
      );
    }
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant