Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 47d5c6e

Browse files
author
deeper
committed
add template_method
1 parent 83f75d0 commit 47d5c6e

File tree

4 files changed

+85
-0
lines changed

4 files changed

+85
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package com.ruoxu.pattern.template_method;
2+
/**
3+
* 程序员专用计算机
4+
*/
5+
public class CoderComputer extends Computer{
6+
7+
@Override
8+
protected void login() {
9+
System.out.println("只需用户密码即可登录");
10+
}
11+
12+
@Override
13+
public boolean strict() {
14+
return false;
15+
}
16+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.ruoxu.pattern.template_method;
2+
3+
public abstract class Computer {
4+
public final void startUp(){ // 注意: 该方法为final,防止算法框架被篡改。
5+
System.out.println("=== start ===");
6+
powerOn();
7+
checkHardware();
8+
loadOS();
9+
10+
if(strict()){
11+
login();
12+
}
13+
14+
System.out.println("=== 启动完毕 ===");
15+
}
16+
17+
private void powerOn(){
18+
System.out.println("开启电源");
19+
}
20+
21+
private void checkHardware(){
22+
System.out.println("硬件检查");
23+
}
24+
25+
private void loadOS(){
26+
System.out.println("载入操作系统");
27+
}
28+
29+
protected abstract void login();
30+
31+
public boolean strict(){//是否严格
32+
return true;
33+
}
34+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.ruoxu.pattern.template_method;
2+
/**
3+
* 模板方法模式
4+
* 定义: 定义一个操作中的算法的框架,而将一些步骤延迟到子类中,使得子类可以不改变一个算法的结构即可重新定义改算法的某些特定步骤。
5+
* 案例:开源中国APP中BaseActivity的设计
6+
* 使用场景:
7+
* (1)多个子类有公有的方法,并且逻辑基本相同时。
8+
* (2)重要,复杂的算法,可以把【核心算法】设计为模板方法,周边的相关细节功能则由各个子类实现。
9+
* (3)重构时,模板方法是一个经常使用的模式,把相同的代码抽取到父类中,然后通过钩子函数约束其行为。
10+
* 总结:
11+
* 模板方法模式用4个字概括就是:流程封装,也就是把固定的流程封装到一个final函数中,并让子类能够定制流程中的某些步骤。
12+
*/
13+
public class Demo {
14+
public static void main(String[] args) {
15+
Computer computer1 = new CoderComputer();
16+
computer1.startUp();
17+
18+
System.out.println();
19+
20+
Computer computer2 = new MilitaryComputer();
21+
computer2.startUp();
22+
}
23+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package com.ruoxu.pattern.template_method;
2+
/**
3+
* 军用计算机
4+
*/
5+
public class MilitaryComputer extends Computer{
6+
7+
@Override
8+
protected void login() {
9+
System.out.println("输入双重密码加密和指纹识别的方式登录");
10+
}
11+
12+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /