• 模板方法模式(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();
        }
    }
  • 相关阅读:
    JVM
    SpringDataES
    Lucene
    linux下如何实现mysql数据库每天自动备份定时备份
    java的finalize()函数
    Java代码优化(长期更新)
    HashMap实现原理及源码分析
    Java中的equals和hashCode方法详解
    java中JVM的原理
    Java程序员应该了解的10个设计原则
  • 原文地址:https://www.cnblogs.com/fuckingPangzi/p/15740260.html
Copyright © 2020-2023  润新知