通过模版类把公共内容进行抽离封装、提供给其他子类继承使用
主要解决:一些方法通用,却在每一个子类都重新写了这一方法。
何时使用:有一些通用的方法。
如何解决:将这些通用算法抽象出来。
关键代码:在抽象类实现,其他步骤在子类实现。
应用实例:
1、在造房子的时候,地基、走线、水管都一样,只有在建筑的后期才有加壁橱加栅栏等差异。
2、西游记里面菩萨定好的 81 难,这就是一个顶层的逻辑骨架。
提示框案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
</html>
<script>
class Alert{
constructor(data){
const { content, close, confirm, success, fail } = data;
this.content = content;
// 提示框面板
this.panel = document.createElement('div')
// 提示内容组件
this.contentNode = document.createElement('p')
this.contentNode.innerHTML = content;
// 创建确认按钮组件
this.confirmBtn = document.createElement('span')
this.confirmBtn.innerHTML = confirm || '确认'
// 创建关闭按钮组件
this.closeBtn = document.createElement('b')
this.closeBtn.innerHTML = close || '关闭'
// 事件绑定
this.success = success || function(){}
this.fail = fail || function(){}
}
init(){
this.panel.appendChild(this.contentNode)
this.panel.appendChild(this.confirmBtn)
this.panel.appendChild(this.closeBtn)
document.body.appendChild(this.panel)
this.bindEvent()
}
bindEvent(){
this.confirmBtn.onclick = () =>{
this.success()
this.hide()
}
this.closeBtn.onclick = () =>{
this.fail()
this.hide()
}
}
hide(){
this.panel.style.display = 'none'
}
show(){
this.panel.style.display = 'block'
}
}
class MessageBox extends Alert{
constructor({ confirm }){
super({
content:"您是否需要执行删除操作??",
confirm:"确认",
close:"取消",
success:confirm,
})
}
}
function confirms(){
console.log('用户按了确认')
}
let messageBox = new MessageBox({
confirm:confirms
})
messageBox.init()
</script>
总结
优点
- 公共的抽离、扩展性好