相关文章
【合集】Java设计模式
模板方法模式
抽象类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public static abstract class AbstractClass {
// 加final保护 不能被子类重写
public final void cookProcess() {
this.pourOil();
this.heatOil();
this.pourVegetable();
this.pourSauce();
this.fry();
}
public void pourOil() {
System.out.println("倒油");
}
public void heatOil() {
System.out.println("热油");
}
public abstract void pourVegetable();
public abstract void pourSauce();
public void fry() {
System.out.println("炒啊炒啊炒到熟啊");
}
}
|
具体方法类
1
2
3
4
5
6
7
8
|
public static class ConcreteClassBaoCai extends AbstractClass {
public void pourVegetable() {
System.out.println("下锅的蔬菜是包菜");
}
public void pourSauce() {
System.out.println("下锅的酱料是辣椒");
}
}
|
1
2
3
4
5
6
7
8
|
public static class ConcreteClassCaiXin extends AbstractClass {
public void pourVegetable() {
System.out.println("下锅的蔬菜是菜心");
}
public void pourSauce() {
System.out.println("下锅的酱料是蒜蓉");
}
}
|
客户端调用
1
2
3
4
5
|
ConcreteClassBaoCai baoCai = new ConcreteClassBaoCai();
baoCai.cookProcess();
ConcreteClassCaiXin caiXin = new ConcreteClassCaiXin();
caiXin.cookProcess();
|
应用
{@link InputStream#read()}每次读取一个字节数据,进行了抽象,有子类来实现