# 面试官:聊一下你项目中的设计模式吧
**引言:设计模式的重要性**
在当今的软件开发领域中,设计模式无异于程序员的“武林秘籍”。它们是前人在解决特定问题时总结出的最佳实践,能够帮助我们编写出更加高效、可维护和易于扩展的代码。本文将通过实际项目案例,深入探讨我在项目中运用的设计模式,并辅以具体代码实现,让您在面试或实际工作中都能游刃有余。
## **一、单例模式:确保全局唯一实例**
在很多场景下,如数据库连接管理、缓存系统等,我们需要保证在整个应用生命周期中只有一个类的实例存在。这时,单例模式就派上了用场。
```javascript
class Singleton {
static instance = null;
constructor() {
if (!Singleton.instance) {
Singleton.instance = this;
}
return Singleton.instance;
}
// 其他业务方法...
}
// 使用示例:
const instance1 = new Singleton();
const instance2 = new Singleton();
console.log(instance1 === instance2); // 输出:true
```
## **二、工厂模式:封装对象创建过程**
工厂模式提供了一种统一创建对象的方法,隐藏了对象的具体创建逻辑,使客户端无需知道对象是如何被创建出来的。
```javascript
function createVehicle(type) {
switch (type) {
case 'car':
return new Car();
case 'bike':
return new Bike();
default:
throw new Error('Invalid vehicle type');
}
}
class Car {}
class Bike {}
// 使用示例:
const myCar = createVehicle('car');
const myBike = createVehicle('bike');
```
## **三、策略模式:运行时动态选择算法**
策略模式定义了一系列的算法,并将每一个算法封装起来,使得他们可以相互替换。在项目的状态机或者不同的业务规则处理中,常常会使用到此模式。
```javascript
class ShippingStrategy {
calculate(price) {
throw new Error('Method needs to be implemented');
}
}
class FlatRateStrategy extends ShippingStrategy {
calculate(price) {
return price + 5;
}
}
class FreeShippingStrategy extends ShippingStrategy {
calculate(price) {
if (price > 100) {
return 0;
} else {
return price + 10;
}
}
}
// 使用示例:
let strategy = new FlatRateStrategy();
console.log(strategy.calculate(50)); // 输出:55
strategy = new FreeShippingStrategy();
console.log(strategy.calculate(150)); // 输出:0
```
## **四、装饰器模式:增强对象功能**
装饰器模式可以在不改变对象自身的基础上,在程序运行期间向对象添加新的行为或责任。在Web前端开发中,JavaScript的Decorator提案就是其典型应用。
```javascript
// 假设有一个基础组件类
class BaseComponent {
render() {
console.log('Base component rendered');
}
}
// 装饰器类
class LoggingDecorator {
constructor(component) {
this.component = component;
}
render() {
console.log('Logging before render...');
this.component.render();
console.log('Logging after render...');
}
}
// 使用装饰器
let baseComponent = new BaseComponent();
baseComponent = new LoggingDecorator(baseComponent);
baseComponent.render();
// 输出: "Logging before render..."
// "Base component rendered"
// "Logging after render..."
```
## **五、代理模式:控制访问**
代理模式为其他对象提供一个代理以控制对这个对象的访问。例如,在前后端交互时,我们可以利用代理模式来预处理请求或响应数据。
```javascript
class ServerProxy {
getData(url) {
// 实际网络请求
const data = fetch(url).then(res => res.json());
// 可能包含错误处理、缓存策略等
return data;
}
}
const proxy = new ServerProxy();
proxy.getData('/api/data')
.then(data => console.log(data));
```
以上仅是众多设计模式中的一部分实战应用场景。每个设计模式都有其适用场景与价值,熟练掌握并灵活运用这些设计模式,不仅能提高代码质量,更能体现出开发者对于软件设计原则的理解深度。希望这篇文章能帮助您在面试中从容应对设计模式相关问题,也能在日常开发中提升代码的艺术性和实用性。
本文暂时没有评论,来添加一个吧(●'◡'●)