模版设计模式

概述

1
设计了一个固定的开头和结尾的内容,正文内容由子类负责填充;

为什么使用模版

1
使用模版可以将通用的代码提前设计到模版中,从而提升代码的复用性;

在哪里使用

1
在一些框架或特定的技术中可以使用;

如何编写

  1. 写了一个模版方法,需要使用final修饰,目的是让子类直接使用,而不能重写;
  2. 写了一个抽象方法,目的是为了让子类重写,填充内容;

image-20240117165518756

CodeDemo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public abstract class Zwmb {
/*
创建一个作文模板
*/
public final void write(){
System.out.println("这是我的爸爸!");
this.content();
System.out.println("啊!这就是我的爸爸!");
}

public abstract void content();
}


public class Tom extends Zwmb{
@Override
public void content() {
System.out.println("记忆中,他是那么一个人...");
}
}


public class Test {
public static void main(String[] args) {
// 创建子类对象
Tom t = new Tom();
t.write();
}
}