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

装饰器模式 #218

Open
louzhedong opened this issue Jun 12, 2020 · 0 comments
Open

装饰器模式 #218

louzhedong opened this issue Jun 12, 2020 · 0 comments

Comments

@louzhedong
Copy link
Owner

装饰器模式

动态地给一个对象添加一些额外的职责。

优点:

装饰类和被装饰类可以独立开发,不会互相耦合。

缺点:

多层装饰会比较复杂

实现
Java
/**
 * 抽象构件
 **/
public abstract class Component {
    public abstract void operate();
}

/**
 * 具体构件
 **/
public class ConcreteComponent extends Component {
    @Override
    public void operate() {

    }
}

/**
 * 抽象修饰器
 **/
public abstract class Decorator extends Component{
    private Component component = null;

    public Decorator(Component _component) {
        this.component = _component;
    }

    @Override
    public void operate() {
        this.component.operate();
    }
}

/**
 * 具体修饰器
 **/
public class ConcreteDecorator extends Decorator{
    public ConcreteDecorator(Component _component) {
        super(_component);
    }

    private void method() {}

    @Override
    public void operate() {
        this.method();
        super.operate();
    }
}

public class Client {
    public static void main(String[] args) {
        Component component = new ConcreteComponent();

        component = new ConcreteDecorator(component);

        component.operate();
    }
}
JavaScript
Function.prototype.before = function (beforefn) {
  const _this = this;
  return function () {
    beforefn.apply(this, arguments);
    return _this.apply(this, arguments);
  }
}

Function.prototype.after = function (afterfn) {
  const _this = this;
  return function () {
    const ret = _this.apply(this, arguments);
    afterfn.apply(this, arguments);
    return ret;
  }
}

// 例子
Function.prototype.before = function (beforefn) {
  const _this = this;
  return function () {
    if (beforefn.apply(this, arguments) === false) {
      return;
    }
    return _this.apply(this, arguments);
  }
}

const validata = function () {
  if (username.value === '') {
    return false;
  }
  if (password.value === '') {
    return false;
  }
}

let formSubmit = function () {
  const param = {
    username: username.value,
    password: password.value
  }
  ajax('http://aa.com', param);
}

formSubmit = formSubmit.before(validata);

submitBtn.onclick = function () {
  formSubmit();
}
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