Luckylau's Blog

设计模式之模版方法模式

​ 一个抽象类公开定义了执行它的方法的方式/模板。它的子类可以按需要重写方法实现,但调用将以抽象类中定义的方式进行。这种类型的设计模式属于行为型模式。

​ 子类通常不关心全局(比如整个流程、提纲、步骤),而只负责”填空“;”填空“通过实现或重写父类的方法来实现。从父类角度,全局性的规范约束掌握在自己手中,具体来说通过模板方法来约束,从而能够尽量简化子类的复杂度。父类并不一定是抽象类,模板方法也并不一定是抽象方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public abstract class SchoolPerson {
protected String name;
protected int age;
protected String schoolName;
protected String hometown;
public SchoolPerson(String name, int age, String schoolName, String hometown) {
this.name = name;
this.age = age;
this.schoolName = schoolName;
this.hometown = hometown;
}
public void selfIntroduction() {
myBasicInfo();
myslogan();
}
public abstract void myBasicInfo();
public abstract void mySlogan();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Student extends SchoolPerson {
public Student(String name, int age, String schoolName, String hometown) {
super(name, age, schoolName, hometown);
}
public void myBasicInfo() {
System.out.println("我是一名学生,名叫" + this.name + ", 今年" + this.age + "岁, " + this.hometown + "人, 在" + this.schoolName + "上学。");
}
public void mySlogan() {
System.out.println("在我在" + this.schoolName + "求学的过程中,我一定 好好学习,天天向上!");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Teacher extends SchoolPerson {
public Teacher(String name, int age, String schoolName, String hometown) {
super(name, age, schoolName, hometown);
}
public void myBasicInfo() {
System.out.println("我是一名教师,名叫" + this.name + ", 今年" + this.age + "岁, " + this.hometown + "人, 在" + this.schoolName + "教书。");
}
public void mySlogan() {
System.out.println("在我在" + this.schoolName + "教学的过程中,我一定 为人师表,诲人不倦!");
}
}
1
2
3
4
5
6
7
8
9
public class Client {
public static void main(String[] args) {
SchoolPerson student = new Student("张三", 12, "光明小学", "山东济南");
student.selfIntroduction();
SchoolPerson teacher = new Teacher("李四", 32, "光明小学", "山东青岛");
teacher.selfIntroduction();
}
}
Luckylau wechat
如果对您有价值,看官可以打赏的!