1. 开闭原则
对修改闭合,对扩展开放
- 设计和开发的类、组件或模块能够通过扩展来适应新功能,而不会需要更改现有代码,这有助于降低维护成本和减少对现有系统的干扰。
- 实现这一原则的一种方式是通过抽象类和接口。
2. 非侵入式设计
不修改已有代码
- 减少组件之间的耦合度
- 提高代码的复用性
- 增强代码的稳定性和可维护性
3. 装饰器模式
-
业务逻辑交给装饰器实现
-
装饰器模式将对象的核心功能与可变的功能解耦,以此来动态地增加或移除功能,即使是在运行时。
以下是一个简单的装饰器模式的示例,展示如何动态地为一个对象添加额外的功能:
// 基本的组件
class Coffee {
cost() {
return 5;
}
}
// 装饰器基类
class CoffeeDecorator {
constructor(coffee) {
this._coffee = coffee;
}
cost() {
return this._coffee.cost();
}
}
// 具体的装饰器
class MilkDecorator extends CoffeeDecorator {
cost() {
return super.cost() + 2;
}
}
class SugarDecorator extends CoffeeDecorator {
cost() {
return super.cost() + 1;
}
}
// 使用装饰器
const myCoffee = new Coffee();
console.log('Basic coffee cost:', myCoffee.cost()); // 输出: Basic coffee cost: 5
const milkCoffee = new MilkDecorator(myCoffee);
console.log('Coffee with milk cost:', milkCoffee.cost()); // 输出: Coffee with milk cost: 7
const sugarMilkCoffee = new SugarDecorator(milkCoffee);
console.log('Coffee with milk and sugar cost:', sugarMilkCoffee.cost()); // 输出: Coffee with milk and sugar cost: 8
在这个示例中,Coffee
类表示基本的咖啡,而 MilkDecorator
和 SugarDecorator
类分别为咖啡添加了牛奶和糖的功能。通过将装饰器嵌套在一起,可以动态地组合不同的功能,而不需要修改 Coffee
类本身。