<<设计模式之禅(第二版)>>——第十章

2016-10-14  本文已影响12人  leiiiooo
定义:
通用类图:
模板方法模式通用类图
模板方法模式的拓展:
拓展模板方法模式
public abstract class BaseModel {
  protected abstract void methodOne();

  protected abstract void methodTwo();

  protected abstract void methodThree();

  final void together() {
    methodOne();
    methodTwo();
    if (hook()) {
        methodThree();
    }

  }

  protected Boolean hook() {

    return true;
  }
}
public class ModelOne extends BaseModel {
  private boolean tag = true;// 默认实现方法三

  @Override
  protected void methodOne() {
    // TODO Auto-generated method stub

  }

  @Override
  protected void methodTwo() {
    // TODO Auto-generated method stub

  }

  @Override
  protected void methodThree() {
    // TODO Auto-generated method stub

  }

  @Override
  protected Boolean hook() {
    // TODO Auto-generated method stub
    return this.tag;
  }

  // 提供设置标志位的方法
  public boolean setTag(Boolean tag) {
    try {
        this.tag = tag;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }
    return true;
  }
}
父类怎么调用子类中的方法(强烈不建议使用,违背模板方法模式。子类定义出自身的特有方式,通过父类中定义的公共方法确认执行顺序)
上一篇 下一篇

猜你喜欢

热点阅读