设计模式之其他设计模式(7-1)

143 阅读1分钟

1、原型模式

image.png

image.png

image.png

  • 自己敲一下
// 原型模式

const prototype = {
  getName: function () {
    return this.first + " " + this.last;
  },
  say: function () {
    alert("say");
  },
};

// 基于原型创建 X
let x = Object.create(prototype);
x.first = "A";
x.last = "B";
alert(x.getName());
x.say();

// 基于原型创建 Y
let y = Object.create(prototype);
y.first = "C";
y.last = "D";
alert(y.getName());
y.say();
  • 结果展示 弹出预期的结果

image.png

image.png

2、桥接模式

image.png

image.png

image.png

image.png

  • 自己 敲一遍
// 桥接模式

class Color {
  constructor(name) {
    this.name = name;
  }
}

class Shap {
  constructor(name, color) {
    this.name = name;
    this.color = color;
  }
  draw() {
    console.log(`${this.color.name} ${this.name}`);
  }
}

const red = new Color("red");
const yellow = new Color("yellow");

const circle = new Shap("circle", red);
circle.draw();
const triangle = new Shap("triangle", yellow);
triangle.draw();
  • 结果展示

image.png

image.png

3、组合模式

image.png

image.png

image.png

image.png

image.png

4、享元模式

image.png

image.png

image.png

5、策略模式

image.png

image.png

image.png

  • 自己敲一下

image.png

  • 结果 ok的

image.png

  • 策略模式 更改一下
// 策略模式 优化一下

class OrdinaryUser {
  buy() {
    console.log("普通 用户购买");
  }
}

class MemuberUser {
  buy() {
    console.log("memuber 用户购买");
  }
}

class VipUser {
  buy() {
    console.log("vip 用户购买");
  }
}

let u1 = new OrdinaryUser();
u1.buy();
let u2 = new MemuberUser();
u2.buy();
let u3 = new VipUser();
u3.buy();

image.png

image.png

6、模版方法 模式

  • 常用思想

image.png

7、职责链 模式

image.png

image.png

  • 自己敲一下
// 职责链 模式
class Action {
  constructor(name) {
    this.name = name;
    this.nextAction = null;
  }

  setNextAction(action) {
    this.nextAction = action;
  }

  handle() {
    console.log(`${this.name} 审批`);
    if (this.nextAction != "null") {
      this.nextAction.handle();
    }
  }
}

// 测试代码
let a1 = new Action("组长");
let a2 = new Action("经理");
let a3 = new Action("总监");
a1.setNextAction(a2);
a2.setNextAction(a3);
a1.handle();
  • 结果

image.png

image.png

image.png