模板方法模式就是在父(基)類定義模板(流程),而具體的處理環節交給子類來實現 附錄 github.com/maikec/patt… 個人GitHub設計模式案例 聲明 引用該文檔請註明出處 ...
模板方法模式就是在父(基)類定義模板(流程),而具體的處理環節交給子類來實現
/** * @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設計模式案例
聲明
引用該文檔請註明出處