Description: Defines an algorithm skeleton in an operation, delaying some of the steps into subclasses. Prepare a draw template, implement part of the logic, and then declare some common abstract methods that require different implementations for subclasses.
Scenario: For multiple businesses, many functions in their business are similar, and some functions need to be implemented on their own. This allows us to use template method patterns, break down functions, extract smaller blocks of functionality, and reduce repetitive code. I. Role and role
role |
function |
Abstract templates |
Defines the different blocks of functionality that subclasses need to implement, and the functional blocks shared by subclasses |
Specific templates |
Implement their own different blocks of functionality |
second, brew hot drinks
In the coffee and lemon green tea, they have some of the same function-boil water, pour into the cup. and the ingredients and spices are different.
Hot Drinks
There is a method that cannot be overridden by a subclass Preparerecipe () for the function of a brewing beverage
Public abstract class Beverage {
final void Preparerecipe () {
//final means that subclasses cannot override this method
Boilwater ();
Brew ();
Pourincup ();
Addcondiments ();
}
The brew content and added ingredients are all subclasses to implement
abstract void Brew ();
abstract void addcondiments ();
private void Pourincup () {
System.out.println ("Pour hot drink into cup");
}
private void Boilwater () {
System.out.println ("boil water");
}
Coffee
Coffee Brewing public
class Coffee extends beverage {
@Override
void Brew () {
System.out.println ("Add Coffee") ;
}
@Override
void Addcondiments () {
System.out.println ("Add Sugar");
}
Lemon Green Tea
Lemon Green Tea Brewing public
class Teas extends Beverage {
@Override
protected void Brew () {
System.out.println (" Into the tea ");
}
@Override
protected void addcondiments () {
System.out.println ("Add lemon slice");
}
Brewing Drinks
public static void Main (string[] args) {
System.out.println ("Bubble coffee");
Beverage coffee = new coffee ();
Coffee.preparerecipe ();
System.out.println ("Bubble lemon green Tea");
Beverage tea = new Tea ();
Tea.preparerecipe ();
}
Output
Brew coffee, boil water,
add coffee,
pour the hot drinks into the cup,
add sugar,
lemon green tea,
boil
the tea,
pour the hot drink into the cup
.
more patterns: one day a design pattern-classification and six major principles
more Source: Https://github.com/oDevilo/Java-Base