模版方法:通过实现类扩展的方法来完成业务逻辑。
1. 创建实例的模板
- package designpattern;
- public abstract class GenericWithCreate<T> {
- final T element;
- GenericWithCreate() {
- element = create();
- }
- abstract T create();
- }
- class X {}
2. X类创建的具体实现
- package designpattern;
- public class Creator extends GenericWithCreate<X> {
- @Override
- X create() {
- return new X();
- }
- void f() {
- System.out.println(element.getClass().getName());
- }
- }
3. 测试代码
- package designpattern;
- public class CreatorGeneric {
- public static void main(String[] args) {
- Creator c = new Creator();
- c.f();
- }
- }
- //output
- designpattern.X