模板方法模式(Template Pattern)-行为型(Behavior)-很常用的一个设计模式

之前看Spring源码,里面的AbstractXmlApplicationContext,就是使用的模板方法模式,所以在这里,打算,写个简单的demo出来玩玩

 

 

定义:在抽象类里面公开定义它的抽象模板,在子类去实现它的抽象方法,然后业务按照模板去执行。

代码实现:

public class TemplateMethodPraticeDay6 {

    /**
     * 抽象类,在里面公开定义业务模板。
     */
    public static abstract class AbstractXmlFactory{

        public int loadBeanDefinitions(){
            String resources = getConfigResources();
            System.out.println("加载resources文件:"+resources);
            return 0;
        }

        public AbstractXmlFactory() {
        }

        public AbstractXmlFactory(AbstractXmlFactory abstractXmlFactory) {
            this();
            System.out.println("set parent的factory");
        }

        /**
         * 给子类去实现
         * @return
         */
        protected abstract String getConfigResources();
    }

    /**
     * 实现类,在里面实现getConfigResources()方法
     */
    public static class ClassPathXmlApplicationContext extends AbstractXmlFactory{

        private String[] resources;

        public ClassPathXmlApplicationContext() {
        }

        public ClassPathXmlApplicationContext(String[] resources) {
            this(resources,true,null);
        }

        public ClassPathXmlApplicationContext(String[] resources, boolean refresh, @Nullable ClassPathXmlApplicationContext context) {
            super(context);
            this.resources = resources;
            if (refresh){
                System.out.println("销毁已存在的BeanFactory,创建新的BeanFactory");
            }
        }

        @Override
        protected String getConfigResources() {
            return Arrays.toString(resources);
        }
    }

    public static void main(String[] args) {
        AbstractXmlFactory context = new ClassPathXmlApplicationContext(new String[]{"beanDefinition.xml"});
        context.loadBeanDefinitions();
    }
}

 

posted @ 2021-12-28 13:37  正能量教官  阅读(29)  评论(0编辑  收藏  举报