模板方法模式
模板方法模式
模板方法模式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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理