• 模板方法模式


    模板方法模式

    模板方法模式Template Method Pattern定义了如何执行某些算法的框架,一个抽象类公开定义了执行它的方法的方式或模板,其子类可以按需要重写方法实现,也可以调用将以抽象类中定义的方式进行,这种类型的设计模式属于行为型模式。

    描述

    模板方法模式是一种行为设计模式,用于定义操作中算法的程序框架,从而将某些步骤推迟到子类中,其可以重新定义算法的某些步骤,而无需更改算法的结构。

    优点

    • 封装不变部分,扩展可变部分,提高了拓展性。
    • 提取公共代码,便于维护,提高代码复用性。
    • 行为由父类控制,子类实现,实现了反向控制 ,符合开闭原则。

    缺点

    • 每一个不同的实现都需要一个子类来实现,导致类的个数增加,使得系统更加庞大。

    适用环境

    • 有多个子类共有的方法,且逻辑相同。
    • 重要的、复杂的方法,可以考虑作为模板方法。

    实现

    class Builder {
        build() {
            this.start();
            this.lint();
            this.assemble();
            this.deploy();
        }
    }
    
    class AndroidBuilder extends Builder {
        constructor(){
            super();
        }
        start() {
            console.log("Ready to start build android");
        }
        
        lint() {
            console.log("Linting the android code");
        }
        
        assemble() {
            console.log("Assembling the android build");
        }
        
        deploy() {
            console.log("Deploying android build to server");
        }
    }
    
    class IosBuilder extends Builder {
        constructor(){
            super();
        }
        start() {
            console.log("Ready to start build ios");
        }
        
        lint() {
            console.log("Linting the ios code");
        }
        
        assemble() {
            console.log("Assembling the ios build");
        }
        
        deploy() {
            console.log("Deploying ios build to server");
        }
    }
    
    (function(){
        const androidBuilder = new AndroidBuilder();
        androidBuilder.build();
        // Ready to start build android
        // Linting the android code
        // Assembling the android build
        // Deploying android build to server
    
        const iosBuilder = new IosBuilder();
        iosBuilder.build();
        // Ready to start build ios
        // Linting the ios code
        // Assembling the ios build
        // Deploying ios build to server
    })();
    

    每日一题

    https://github.com/WindrunnerMax/EveryDay
    

    参考

    https://juejin.im/post/6844903615476269064
    https://www.runoob.com/design-pattern/template-pattern.html
    https://github.com/sohamkamani/javascript-design-patterns-for-humans#-template-method
    
  • 相关阅读:
    在做城市选择界面时,获取首字母并转化为大写,发现好多网上的代码,个别汉字不能转为拼音(漯河、鄢陵等)
    微信小程序之开发的坑
    前端学习之学习网站
    前端学习之Angular cli
    前端学习之npm国内镜像cnpm和yarn的快速安装
    eclipse Team之pull操作从GitLab上更新项目到本地
    前端学习之angular项目的本地运行步骤
    前端学习之vscode脚本禁用的问题
    maven项目启动提示:启动过滤器异常
    前端学习之Node.js安装及环境配置
  • 原文地址:https://www.cnblogs.com/WindrunnerMax/p/13815916.html
Copyright © 2020-2023  润新知