设计模式5——模板方法模式

1、定义
模板方法模式由两部分结构组成,第一部分是抽象父类,第二部分是具体的实现子类。

2、核心
在抽象父类中封装子类的算法框架,它的 init方法可作为一个算法的模板,指导子类以何种顺序去执行哪些方法。
由父类分离出公共部分,要求子类重写某些父类的(易变化的)抽象方法

3、实现
模板方法模式一般的实现方式为继承

以运动作为例子,运动有比较通用的一些处理,这部分可以抽离开来,在父类中实现。具体某项运动的特殊性则有自类来重写实现。
最终子类直接调用父类的模板函数来执行

例子:采用canvas,就是为了展示这个设计模式
`// 所谓模板,就是类的模板,先建立模板,再申明子类并继承父类模板,
// 重新部分方法达到实现自定义的效果
// 简单理解:父类模板 + 子类继承重写

class templateDraw{
constructor(canvas){
this.ctx = canvas.getContext('2d')
}
start(){
throw new Error('此方法为父类方法,不可直接使用,需要子类重写后进行调用。')
}
begin(){
this.ctx.beginPath()
}
drawLine(start, end){
this.ctx.moveTo(start.x, start.y)
this.ctx.lineTo(end.x, end.y)
}
fillRect(start, end ){
this.ctx.fillRect(start.x, start.y, end.x, end.y )
}
stroke(){
this.ctx.stroke()
}

}

class myCan extends templateDraw{
start(){
this.begin()
this.drawLine({x:0,y:0}, {x:100, y:100})
this.stroke()
}
}

let can = new myCan(document.querySelector('canvas'))
can.start()`

posted @   Math点PI  阅读(16)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示