四、装饰器模式
装饰器模式,希望在不改变原对象的基础上,通过对其拓展功能和属性来实现更复杂的逻辑
1、装饰器模式例子
假设有一家店在卖一种车,价格为10万元,如果用户需要在此基础上加装一些配置则需要加钱。比如加热座椅配置需要两万元,电动后视镜需要0.8万元等。
// 一般写法
代码语言:javascript复制<!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>
<script>
function Car() {
this.price = 10;
}
Car.prototype = {
addHeatSeat: () => {
this.hasHeatSeat = true;
this.price = 2
},
addAutoMirror: () => {
this.hasAutoMirror = true
this.price = 0.8
}
}
var car1 = new Car()
console.log(this.price) // 10
car1.addHeatSeat()
car1.addAutoMirror()
console.log(car1.price) // 12.8
</script>
</head>
<body>
</body>
</html>
// 装饰器模式
代码语言:javascript复制<!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>
<script>
function Car() {
this.price = 10;
}
// 装饰器模式减少了对构造函数的操作
function carWithHeatSeat(carClass) {
carClass.hasHeatSeat = true
carClass.price = 2
}
function carWithAutoMirror(carClass) {
carClass.hasAutoMirror = true
carClass.price = 0.8
}
var car2 = new Car()
console.log(this.price) // 10
carWithHeatSeat(car2)
carWithAutoMirror(car2)
console.log(car2.price) // 12.8
</script>
</head>
<body>
</body>
</html>