设计模式之模板方法模式

概念

模板方法模式(Template Method),定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤

优点

  • 在基类中定义算法的不变部分提升了代码复用性
  • 将通用行为封装在一个地方简化了代码维护
  • 允许子类覆盖算法的特定步骤增强了代码灵活性

示例

以偷东西为例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public abstract class StealingMethod {

protected abstract String pickTarget();

protected abstract void confuseTarget(String target);

protected abstract void stealTheItem(String target);
// 模板方法
public final void steal() {
var target = pickTarget();
LOGGER.info("The target has been chosen as {}.", target);
confuseTarget(target);
stealTheItem(target);
}
}

偷东西方式一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class SubtleMethod extends StealingMethod {

@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);
}
}

偷东西方式二

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Slf4j
public class HitAndRunMethod extends StealingMethod {

@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!");
}
}

小偷

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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;
}
}

应用

1
2
3
4
5
6
public static void main(String[] args) {
var thief = new HalflingThief(new HitAndRunMethod());
thief.steal();
thief.changeMethod(new SubtleMethod());
thief.steal();
}

输出

1
2
3
4
5
6
11:06:01.721 [main] INFO com.iluwatar.templatemethod.StealingMethod -- The target has been chosen as old goblin woman.
11:06:01.723 [main] INFO com.iluwatar.templatemethod.HitAndRunMethod -- Approach the old goblin woman from behind.
11:06:01.723 [main] INFO com.iluwatar.templatemethod.HitAndRunMethod -- Grab the handbag and run away fast!
11:06:01.723 [main] INFO com.iluwatar.templatemethod.StealingMethod -- The target has been chosen as shop keeper.
11:06:01.723 [main] INFO com.iluwatar.templatemethod.SubtleMethod -- Approach the shop keeper with tears running and hug him!
11:06:01.723 [main] INFO com.iluwatar.templatemethod.SubtleMethod -- While in close contact grab the shop keeper's wallet.

注意

  • 可能导致类的数量增加,使系统更加复杂
  • 需要仔细设计,以确保公开给子类的步骤是有用和有意义的

设计模式之模板方法模式
http://s1mplecode.com/design-pattern/template-method.html
作者
Jago
发布于
2024年12月18日
许可协议