zoukankan      html  css  js  c++  java
  • 设计模式——模板方法模式

    模板方法模式就是在父(基)类定义模板(流程),而具体的处理环节交给子类来实现

    /**
     * @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设计模式案例

    声明

    引用该文档请注明出处

  • 相关阅读:
    使用awrrpt.sql 生成AWR报告
    oracle简单物化视图
    oracle 查询重复内容
    windows server 2008 服务器 oracle11g降级oracle10g遇到的种种问题
    简单js条码生成器
    tomcat服务器禁用非post、get方法的坑
    委托和事件
    消息队列(Message Queue)简介及其使用
    架构师修炼之道
    Xcode7 使用NSurl发送HTTP请求报错
  • 原文地址:https://www.cnblogs.com/imaikce/p/10882227.html
Copyright © 2011-2022 走看看