Template Method

Keywords: brew

Template Method behavioral class 1

Intent 2

Define the skeleton of an algorithm in a method, and delay some steps to the subclass. The template method allows subclasses to redefine some steps of the algorithm without changing the structure of the algorithm

Motivation 3

Ensure that the structure of the algorithm remains unchanged, and that the subclass provides part of the implementation

Applicability 4

The general situation in the algorithm structure

Structure 5

Participants 6

  • Abstract template is responsible for defining the basic structure of the algorithm
  • ConcreteTemplate implements abstract methods and hook methods defined in AbstractTemplate

Collaborations 7

  1. AbstractTemplate defines an algorithm structure and composition steps, which are composed of one template method and several basic methods
    ->Template method: defines the structure of the algorithm and calls the basic methods contained in it in a certain order
    ->Basic method: a step in the whole algorithm, including the following types
    Abstract methods are declared in AbstractTemplate and implemented by ConcreteTemplate
    Specific methods have been implemented in AbstractTemplate, and can be inherited or overridden in ConcreteTemplate
    Hook method has been implemented in AbstractTemplate, including logical method for judgment and empty method that needs to be rewritten by ConcreteTemplate

Comsequences results 8

  • Advantage
    Encapsulation invariant part
    Provide common part code for easy maintenance
    Behavior is controlled by the parent class and implemented by the child class
  • shortcoming
    Different implementations need to add a new subclass
  • purpose
    There are methods shared by multiple subclasses, and the logic is the same
    Repetitive and complex, which can be considered as the logical structure of the template

Implementation/Sample Code 910

Implementation

AbstractTemplate

public abstract class AbstractTemplate {

	public void templateMethod() {
		abstractMethod();
		hookMethod();
		concreteMethod();
	}
	
	protected void abstractMethod();

	protected void hookMethod();

	private void concreteMethod() {
		// TODO
	}
	
}

ConcreteTemplate

public class ConcreteTemplate extends AbstractTemplate {

	@Override
	public void abstractMethod() {
		// TODO
	}

	@Override
	public void hookMethod() {
		// TODO
	}
	
}

Sample Code

AbstractTemplate

public abstract class CaffeineBeverageWithHook {
    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");
    }

    // The Hook subclass can override this method, but not necessarily
    boolean customerWantsCondiments() {
        return true;
    }
}

ConcreteTemplate

public class CoffeeWithHook extends CaffeineBeverageWithHook {
    @Override
    void brew() {
        System.out.println("Dripping Coffee through filter");
    }

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

    @Override
    public boolean customerWantsCondiments() {
        String answer = getUserInput();

        if (answer.toLowerCase().startsWith("y")) {
            return true;
        } else {
            return false;
        }
    }

    private String getUserInput() {
        String answer = null;

        System.out.println("Would you like milk and sugar with your coffee (y/n)? ");

        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        try {
            answer = in.readLine();
        } catch (IOException ioe) {
            System.out.println("IO error trying to read your answer");
        }
        if (answer == null) {
            return "no";
        }
        return answer;
    }
}
public class TeaWithHook extends CaffeineBeverageWithHook {
    @Override
    void brew() {
        System.out.println("Steeping the tea");
    }

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

    @Override
    public boolean customerWantsCondiments() {
        String answer = getUserInput();

        if (answer.toLowerCase().startsWith("y")) {
            return true;
        } else {
            return false;
        }
    }

    private String getUserInput() {
        String answer = null;

        System.out.println("Would you like lemon with your tea (y/n)? ");

        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        try {
            answer = in.readLine();
        } catch (IOException ioe) {
            System.out.println("IO error trying to read your answer");
        }
        if (answer == null) {
            return "no";
        }
        return answer;
    }
}

Client

public class BeverageTestDrive {
    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();
    }
}

Result

Making tea...
Boiling water
Steeping the tea
Pouring into cup
Would you like lemon with your tea (y/n)? 
y
Adding Lemon

Making coffee...
Boiling water
Dripping Coffee through filter
Pouring into cup
Would you like milk and sugar with your coffee (y/n)? 
n

Known Uses 11

Related Patterns 12

  1. Pattern classification attribution ↩︎

  2. Intention: describe the role of the pattern and the definition of the pattern ↩︎

  3. Motivation: gives the problem and specific scenarios of how to solve it ↩︎

  4. Applicability: describe where patterns can be applied ↩︎

  5. Structure: provides a diagram showing the relationships between classes participating in this pattern ↩︎

  6. Participants: describe the responsibilities and roles of the classes and objects involved in this design in the pattern ↩︎

  7. Collaboration: Tell participants how to collaborate in this model ↩︎

  8. Results: describe the possible effects after using this mode, good and bad ↩︎

  9. Implementation: provides the skills needed to implement the pattern, as well as the problems to be faced with carefully ↩︎

  10. Example code: provide snippets of code ↩︎

  11. Known applications: used to describe pattern examples that have been found in real systems ↩︎

  12. Related pattern: describes the relationship between this pattern and other patterns ↩︎

27 original articles published, praised 0, and 370 visitors
Private letter follow

Posted by ginginca on Thu, 05 Mar 2020 04:26:25 -0800