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);
    }
    }
    模板方法应该经常为我们所用,因为这样的代码逻辑步骤清晰,程序可读性好,排错起来也很容易,维护很方便.
    我觉得模板模式几乎不能算设计模式,因为代码就应该这样写才对.所以如果你知道这点,就不要继续看模板模式相关的内容了,因为它压根就不算一种设计模式,而应该是我们的习惯.

  • 相关阅读:
    QT与JavaScript互调
    How can I get an object's absolute position on the page in Javascript?
    ollicle.com: Biggerlink – jQuery plugin
    Javascript: Let user select an HTML element like Firebug?综述
    josscrowcroft / Simple-JavaScript-DOM-Inspector
    Advanced Customization of the jQuery Mobile Buttons | Appcropolis
    jquery-plugin-biggerLink,highLight-层加亮_andy 阳光生活_百度空间
    Highlight On Mouseover Effect With JQuery
    Quick Tip: Outline Elements on Hover
    How to get the xpath by clicking an html element
  • 原文地址:https://www.cnblogs.com/wangxuejian/p/10597433.html
Copyright © 2011-2022 走看看