模板方法模式就是在父(基)类定义模板(流程),而具体的处理环节交给子类来实现
/** * @author maikec * @date 2019/5/10 */ public abstract class AbstractDisplay { private final Integer PRINT_COUNT =5; /** * 打开操作 */ protected abstract void open(); /** * 打印操作 */ protected abstract void print(); /** * 关闭操作 */ protected abstract void close(); /** * 定义模板 */ public final void display(){ open(); for (int i = 0; i < PRINT_COUNT; i++) { print(); } close(); } } /** * @author maikec * @date 2019/5/10 */ public class CharDisplay extends AbstractDisplay { private final Character aChar; public CharDisplay(Character aChar){ if (null == aChar){ throw new IllegalArgumentException( "Character cannot be null" ); } this.aChar = aChar; } @Override public void open() { System.out.println( "Open Char " ); } @Override public void print() { System.out.println( aChar.charValue() ); } @Override public void close() { System.out.println( "Close Char" ); } } /** * @author maikec * @date 2019/5/10 */ public class StringDisplay extends AbstractDisplay { private final String string ; public StringDisplay(String string){ if (null == string){ throw new IllegalArgumentException( "String cannot be null" ); } this.string = string; } @Override public void open() { System.out.println( "Open String" ); } @Override public void print() { System.out.println( string ); } @Override public void close() { System.out.println( "Close String" ); } } /** * @author maikec * @date 2019/5/10 */ public class TemplateDemo { public static void main(String[] args) { AbstractDisplay display = new CharDisplay( '*' ); display.display(); AbstractDisplay stringDisplay = new StringDisplay( "Hi" ); stringDisplay.display(); } }
附录
github.com/maikec/patt… 个人GitHub设计模式案例
声明
引用该文档请注明出处