1.场景问题解决
1.1 场景描述
1.2 OO设计
1.3 需求变动
1.4 带来问题
2.用设计模式改进
2.1 分析
2.2 重新设计
2.3 源码-不带Hook
- Drink(模板抽象类)
public abstract class Drink {
final void prepareRecipe() {
boilWater();
brew();
pourInCup();
addCondiments();
}
abstract void brew();
abstract void addCondiments();
void boilWater() {
System.out.println("Boiling water");
}
void pourInCup() {
System.out.println("Pouring into cup");
}
}
- 具体实现类Drink和Tea
public class Coffee extends Drink {
public void brew() {
System.out.println("Dripping Coffee through filter");
}
public void addCondiments() {
System.out.println("Adding Sugar and Milk");
}
}
public class Tea extends Drink {
public void brew() {
System.out.println("Steeping the tea");
}
public void addCondiments() {
System.out.println("Adding Lemon");
}
}
- 测试类 TestDrink
public class TestDrink {
public static void main(String[] args) {
Tea tea = new Tea();
Coffee coffee = new Coffee();
System.out.println("\nMaking tea...");
tea.prepareRecipe();
System.out.println("\nMaking coffee...");
coffee.prepareRecipe();
}
}
2.4 带Hook
- DrinkWithHook
public abstract class DrinkWithHook {
void prepareRecipe() {
boilWater();
brew();
pourInCup();
if (customerWantsCondiments()) {
addCondiments();
}
}
abstract void brew();
abstract void addCondiments();
void boilWater() {
System.out.println("Boiling water");
}
void pourInCup() {
System.out.println("Pouring into cup");
}
boolean customerWantsCondiments() {
return true;
}
}
- 模板具体实现 CoffeeWithHook 和TeaWithHook
public class CoffeeWithHook extends DrinkWithHook {
public void brew() {
System.out.println("Dripping Coffee through filter");
}
public void addCondiments() {
System.out.println("Adding Sugar and Milk");
}
public boolean customerWantsCondiments() {
return false;
}
}
public class TeaWithHook extends DrinkWithHook {
public void brew() {
System.out.println("Steeping the tea");
}
public void addCondiments() {
System.out.println("Adding Lemon");
}
public boolean customerWantsCondiments() {
return true;
}
}
- 测试类 TestHookDrink
public class TestHookDrink {
public static void main(String[] args) {
TeaWithHook teaHook = new TeaWithHook();
CoffeeWithHook coffeeHook = new CoffeeWithHook();
System.out.println("\nMaking tea...");
teaHook.prepareRecipe();
System.out.println("\nMaking coffee...");
coffeeHook.prepareRecipe();
}
}
3.设计模式总结
3.1 定义
*模板方法:*封装了一个算法步骤,并允许子类为一个或多个步骤方法提供实现.
模板模式可以在使子类在不改变算法结构的情况下,重新定义算法中的某些步骤.
3.2 好莱坞原则
好莱坞原则: 别调用我们,我们会调用你 .
意义: 高层无需知道调用底层的细节,解耦.
3.2 分析思路
4. 设计模式使用场景及注意
- interface Comparable
- abstract class AbstractQueuedSynchronizer (AQS)
5.参考文章
内容总计于HeadFirst设计模式及相关视频