zoukankan      html  css  js  c++  java
  • 模板模式

    在不了解模板模式前,我以为它有多深奥多神秘呢,原来我们每天都在用.

    模板模式,说白了,就是在一个方法中按照逻辑先后,把每个步骤用一个子方法包装起来,而本方法依次调用这些子方法,达到按清晰的顺序执行各步骤的目的.

    比如SpringBoot启动流程中的configureEnvironment()方法就是一个简单的模板方法.

    protected void configureEnvironment(ConfigurableEnvironment environment,
    String[] args) {
    configurePropertySources(environment, args);
    configureProfiles(environment, args);
    }
    如上:该方法规定了要先执行configurePropertySources()方法,后执行configureProfiles()方法.至于具体代码则在两个子方法中实行,不管它事.
    再比如:run()方法就是一个稍微大的模板方法,它规定了启动SpringBoot项目的流程:
    public ConfigurableApplicationContext run(String... args) {
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    ConfigurableApplicationContext context = null;
    FailureAnalyzers analyzers = null;
    configureHeadlessProperty();
    SpringApplicationRunListeners listeners = getRunListeners(args);
    listeners.starting();
    try {
    ApplicationArguments applicationArguments = new DefaultApplicationArguments(
    args);
    ConfigurableEnvironment environment = prepareEnvironment(listeners,
    applicationArguments);
    Banner printedBanner = printBanner(environment);
    context = createApplicationContext();
    analyzers = new FailureAnalyzers(context);
    prepareContext(context, environment, listeners, applicationArguments,
    printedBanner);
    refreshContext(context);
    afterRefresh(context, applicationArguments);
    listeners.finished(context, null);
    stopWatch.stop();
    if (this.logStartupInfo) {
    new StartupInfoLogger(this.mainApplicationClass)
    .logStarted(getApplicationLog(), stopWatch);
    }
    return context;
    }
    catch (Throwable ex) {
    handleRunFailure(context, listeners, analyzers, ex);
    throw new IllegalStateException(ex);
    }
    }
    模板方法应该经常为我们所用,因为这样的代码逻辑步骤清晰,程序可读性好,排错起来也很容易,维护很方便.
    我觉得模板模式几乎不能算设计模式,因为代码就应该这样写才对.所以如果你知道这点,就不要继续看模板模式相关的内容了,因为它压根就不算一种设计模式,而应该是我们的习惯.

  • 相关阅读:
    也谈用反射实现Enum→String映射:一种重视性能的方法【转载】
    C#对象的浅拷贝,深拷贝【转载】
    int转byte[],byte[]转int
    TF31003:您的用户帐户没有连接到 Team Foundation Server 的权限
    关于枚举的双语显示问题
    浅析C#深拷贝与浅拷贝
    反射枚举变量
    C#路径/文件/目录/I/O常见操作汇总(二)
    【转】正确理解ThreadLocal
    【转】JSP的九个隐含对象
  • 原文地址:https://www.cnblogs.com/wangxuejian/p/10597433.html
Copyright © 2011-2022 走看看