模板模式

2016-05-21  本文已影响19人  keith666

Intent

Structure

template by keith
  1. 代码:
public class Template {
    abstract class Beverage {
        // template method, make it final so that it can not be redefined
        final void prepareRecipe() {
            boilWater();
            brew();
            pourInCup();
            if (wantCondiments())
                addCondiments();
        }

        abstract void brew();

        abstract void addCondiments();

        void boilWater() {
            System.out.println("Boiling water");
        }

        void pourInCup() {
            System.out.println("Pouring into a cup");
        }

        // hook method, it is up to subclass to decide whether to override it or not
        // the hook method make the algorithm structure more flexible
        boolean wantCondiments() {
            return true;
        }
    }
    class Coffee extends Beverage {

        @Override
        void brew() {
            System.out.println("Dripping Coffee through filter");
        }

        @Override
        void addCondiments() {
            System.out.println("Adding Sugar and Milk");
        }
    }
    class Tea extends Beverage {

        @Override
        void brew() {
            System.out.println("Steeping the tea");
        }

        @Override
        void addCondiments() {
            System.out.println("Adding Lemon");
        }

        @Override
        boolean wantCondiments() {
            return false;
        }
    }
    private void test() {
        Coffee coffee = new Coffee();
        Tea tea = new Tea();

        coffee.prepareRecipe();
        tea.prepareRecipe();
    }
    public static void main(String[] args) {
        Template template = new Template();
        template.test();
    }
}
  1. Output
Boiling water
Dripping Coffee through filter
Pouring into a cup
Adding Sugar and Milk
Boiling water
Steeping the tea
Pouring into a cup

Refenrence

  1. Design Patterns
  2. 设计模式
上一篇 下一篇

猜你喜欢

热点阅读