装饰器模式

2018-08-18  本文已影响0人  hankchang

装饰器模式


示例

zs1.png zsuml.png
class Circle {
  draw() {
    console.log("画一个圆形");
  }
}
class Decorator {
  constructor(circle) {
    this.circle = circle;
  }
  draw() {
    this.circle.draw();
    this.setRedBorder(circle);
  }
  setRedBorder(circle) {
    console.log("设置红色边框");
  }
}

const circle = new Circle();
circle.draw();

const dec = new Decorator(circle);
dec.draw();

场景

ES7 装饰器

安装 babel 插件

配置.babelrc

@testDec
class Demo {}
function testDec(target) {
  target.isDec = true;
}
console.log(Demo.isDec);
function mixin(...list) {
  return function(target) {
    Object.assign(target.prototype, ...list);
  };
}

const Foo = {
  foo() {
    console.log("foo");
  }
};

@mixin(Foo)
class MyClass {}

const obj = new MyClass();
obj.foo();
function readonly(target, name, descriptor) {
  descriptor.writable = false;
  return descriptor;
}

class Person {
  constructor() {
    this.first = "A";
    this.last = "B";
  }

  @readonly
  name() {
    return `${this.first} ${this.last}`;
  }
}

// 测试
const p = new Person();
console.log(p.name());

p.name = 1; // 报错, name是只读的
function log(target, name, descriptor) {
  const oldValue = descriptor.value;
  descriptor.value = function() {
    console.log(`calling ${name} with`, arguments);
    return oldValue.apply(this, arguments);
  };
  return descriptor;
}

class Math {
  @log
  add(a, b) {
    return a + b;
  }
}

// 测试
const math = new Math();
console.log(math.add(2, 4));

core-decorators

cd1.png cd2.png cd3.png

设计原则验证

上一篇 下一篇

猜你喜欢

热点阅读