模板模式
模板方法模式子一个方法中定义一个算法的骨架,而将一些步骤的实现延迟到子类中.模板方法使得子类在不改变算法结构的情况下,重新定义算法中某些步骤的具体实现.一般由两部分组成,第一部分是抽象父类,第二部分是具体实现的子类.好莱坞原则,子类放弃了监控权,改由父类调用.
-
图例
代码示例
class Person{
dinner(){
this.buy()
this.cook()
this.eat()
}
buy(){
throw new Error('必须由子类实现')
}
cook(){
throw new Error('必须由子类实现')
}
eat(){
throw new Error('必须由子类实现')
}
}
class P1 extends Person{
buy(){
console.log('买材料')
}
cook(){
console.log('做材料')
}
eat(){
console.log('吃饭')
}
}
class P2 extends Person{
buy(){
console.log('买材料')
}
cook(){
console.log('做材料')
}
eat(){
console.log('吃饭')
}
}
let p=new P1();
p.dinner() //买材料 做材料 吃饭
- 应用场景
1.模态框封装
<!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>
<style>
.modal{
width: 400px;
height: 400px;
position: absolute;
top:50%;
left: 50%;
margin-top: -200px;
margin-left: -200px;
background-color: #333;
border-radius: 5px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.modal button{
width: 80px;
height: 30px;
position: absolute;
bottom:20px;
}
.left-btn{
right: 140px;
}
.right-btn{
right: 20px;
}
.close{
position: absolute;
top:10px;
right: 10px;
}
</style>
</head>
<body>
<script src="./模板方法.js"></script>
<script>
new XModel({
title:'标题一',
content:'ssss',
onConfirm:()=>{
alert('confirm')
},
onCancel:()=>{
alert('cancel')
}
})
</script>
</body>
</html>
class Modal{
constructor(options){
this.title=options.title || '标题';
this.content=options.content || '内容';
this.onConfirm=options.onConfirm;
this.onCancel=options.onCancel;
this.init()
this.eventListenner()
}
init(){
this.panel=document.createElement('div')
this.panel.className='modal'
document.body.appendChild(this.panel)
let title=document.createElement('p')
title.innerHTML=this.title
this.panel.appendChild(title)
let content=document.createElement('p')
content.innerHTML=this.content
this.panel.appendChild(content)
let onConfirm=this.confirmBtn=document.createElement('button')
onConfirm.innerHTML='确定'
onConfirm.className='left-btn'
this.panel.appendChild(onConfirm)
let onCancel=this.cancelBtn=document.createElement('button')
onCancel.innerHTML='取消'
onCancel.className='right-btn'
this.panel.appendChild(onCancel)
}
eventListenner(){
this.confirmBtn.addEventListener('click',()=>{
this.onConfirm()
this.hide()
})
this.cancelBtn.addEventListener('click',()=>{
this.onCancel()
this.hide()
})
}
hide(){
this.panel.style.display='none'
}
}
class XModel extends Modal{
init(){
super.init();
this.x=document.createElement('div')
this.x.className='close'
this.x.innerHTML='X'
this.panel.appendChild(this.x)
}
eventListenner(){
super.eventListenner()
this.x.addEventListener('click',()=>{
this.hide()
})
}
}