模板方法模式

模板方法模式UML类图

模板方法模式UML类图

模板方法模式java实现

/**
* StealingMethod defines skeleton for the algorithm.
偷窃Method定义了算法的框架。
*/
public abstract class StealingMethod {

private static final Logger LOGGER = LoggerFactory.getLogger(StealingMethod.class);

protected abstract String pickTarget();

protected abstract void confuseTarget(String target);

protected abstract void stealTheItem(String target);

/**
* Steal.
*/
public void steal() {
//挑选目标
var target = pickTarget();
LOGGER.info("The target has been chosen as {}.", target);
//迷惑目标
confuseTarget(target);
//偷物品
stealTheItem(target);
}
}

/**
* SubtleMethod implementation of {@link StealingMethod}.
微妙
*/
public class SubtleMethod extends StealingMethod {

private static final Logger LOGGER = LoggerFactory.getLogger(SubtleMethod.class);

@Override
protected String pickTarget() {
//店主
return "shop keeper";
}

@Override
protected void confuseTarget(String target) {
//泪流满面地接近店主,拥抱他!
LOGGER.info("Approach the {} with tears running and hug him!", target);
}

@Override
protected void stealTheItem(String target) {
//保持密切联系时,抓住店主的钱包。
LOGGER.info("While in close contact grab the {}'s wallet.", target);
}
}

/**
* HitAndRunMethod implementation of {@link StealingMethod}.
奔跑
*/
public class HitAndRunMethod extends StealingMethod {

private static final Logger LOGGER = LoggerFactory.getLogger(HitAndRunMethod.class);

@Override
protected String pickTarget() {
//小妖精的女人
return "old goblin woman";
}

@Override
protected void confuseTarget(String target) {
//从后面接近老妖精的女人。
LOGGER.info("Approach the {} from behind.", target);
}

@Override
protected void stealTheItem(String target) {
//抓住手提包,快点逃跑!
LOGGER.info("Grab the handbag and run away fast!");
}
}

/**
* Halfling thief uses {@link StealingMethod} to steal.
*/
public class HalflingThief {

private StealingMethod method;

public HalflingThief(StealingMethod method) {
this.method = method;
}

public void steal() {
method.steal();
}

public void changeMethod(StealingMethod method) {
this.method = method;
}
}

/**
* Template Method defines a skeleton for an algorithm. The algorithm subclasses provide
* implementation for the blank parts.
*
* <p>In this example {@link HalflingThief} contains {@link StealingMethod} that can be changed.
* First the thief hits with {@link HitAndRunMethod} and then with {@link SubtleMethod}.
模板方法定义算法的框架。 算法子类为空白部分提供实现。
<p>在此示例中,{@ link HalflingThief}包含可以更改的{@link StealingMethod}。 首先,小偷用{@link HitAndRunMethod}打,然后用{@link SubtleMethod}打。
*/
public class App {

/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
var thief = new HalflingThief(new HitAndRunMethod());
thief.steal();
thief.changeMethod(new SubtleMethod());
thief.steal();
}
}

极客时间

实际应用案例

复用

  • Java IO 类库中InputStream read()
  • Java AbstractList addAll()
    扩展
  • Java HttpServlet 的 service()
  • JUnit TestCase setUp() tearDown()
    回调
  • JdbcTemplate