OnJava8-Examples/patterns/TemplateMethod.java

43 lines
1.0 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// patterns/TemplateMethod.java
// (c)2021 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
// Basic Template Method pattern.
2015-11-03 12:00:44 -08:00
import java.util.stream.*;
2015-06-15 17:47:35 -07:00
abstract class ApplicationFramework {
2017-05-01 14:33:10 -06:00
ApplicationFramework() {
2015-06-15 17:47:35 -07:00
templateMethod();
}
abstract void customize1(int n);
abstract void customize2(int n);
2015-06-15 17:47:35 -07:00
// "private" means automatically "final":
private void templateMethod() {
2015-11-03 12:00:44 -08:00
IntStream.range(0, 5).forEach(
n -> { customize1(n); customize2(n); });
2015-06-15 17:47:35 -07:00
}
}
// Create a new application:
2015-06-15 17:47:35 -07:00
class MyApp extends ApplicationFramework {
@Override void customize1(int n) {
System.out.print("customize1 " + n);
2015-06-15 17:47:35 -07:00
}
@Override void customize2(int n) {
System.out.println(" customize2 " + n);
2015-06-15 17:47:35 -07:00
}
}
public class TemplateMethod {
2016-01-25 18:05:55 -08:00
public static void main(String[] args) {
2015-06-15 17:47:35 -07:00
new MyApp();
}
2015-09-07 11:44:36 -06:00
}
/* Output:
customize1 0 customize2 0
customize1 1 customize2 1
customize1 2 customize2 2
customize1 3 customize2 3
customize1 4 customize2 4
2015-09-07 11:44:36 -06:00
*/