Skip to content

Commit cee2419

Browse files
committed
docs(post): add new post
1 parent a3b5c06 commit cee2419

File tree

1 file changed

+284
-0
lines changed

1 file changed

+284
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,284 @@
1+
---
2+
title: 前端编程范式与设计模式
3+
date: 2024-07-24 19:55:59
4+
categories: '技术'
5+
tags: ['编程范式','设计模式']
6+
cover: https://ilikestudy.cn/oss/2024%2F07%2F24%2F17-c6d2a1a6c1df6ac030a5bc26fc98a157-6fb4de.webp
7+
---
8+
在前端开发中,理解并运用各种编程范式和设计模式有助于提升代码的可维护性、扩展性和可读性。本文将介绍一些常见且有用的编程范式和设计模式,并提供详细的代码示例。
9+
10+
## 编程范式
11+
12+
### 1. 异步编程 (Asynchronous Programming)
13+
14+
异步编程允许程序在等待某些任务完成时继续执行其他任务,从而避免阻塞。前端常见的异步操作包括网络请求、文件读取等。
15+
16+
#### 使用回调函数
17+
```javascript
18+
function fetchData(callback) {
19+
setTimeout(() => {
20+
const data = { id: 1, name: 'John' };
21+
callback(data);
22+
}, 1000);
23+
}
24+
25+
fetchData(data => {
26+
console.log('Data received:', data);
27+
});
28+
```
29+
30+
#### 使用Promise
31+
```javascript
32+
function fetchData() {
33+
return new Promise((resolve, reject) => {
34+
setTimeout(() => {
35+
const data = { id: 1, name: 'John' };
36+
resolve(data);
37+
}, 1000);
38+
});
39+
}
40+
41+
fetchData()
42+
.then(data => {
43+
console.log('Data received:', data);
44+
})
45+
.catch(error => {
46+
console.error('Error:', error);
47+
});
48+
```
49+
50+
#### 使用async/await
51+
```javascript
52+
async function fetchData() {
53+
try {
54+
const response = await fetch('https://api.example.com/data');
55+
const data = await response.json();
56+
console.log('Data received:', data);
57+
} catch (error) {
58+
console.error('Error:', error);
59+
}
60+
}
61+
```
62+
63+
### 2. 面向对象编程 (Object-Oriented Programming, OOP)
64+
65+
面向对象编程通过对象来组织代码,核心概念包括封装、继承和多态。
66+
67+
#### 基本类与继承
68+
```javascript
69+
class Animal {
70+
constructor(name) {
71+
this.name = name;
72+
}
73+
74+
speak() {
75+
console.log(`${this.name} makes a sound.`);
76+
}
77+
}
78+
79+
class Dog extends Animal {
80+
speak() {
81+
console.log(`${this.name} barks.`);
82+
}
83+
}
84+
85+
const dog = new Dog('Rex');
86+
dog.speak(); // Rex barks.
87+
```
88+
89+
#### 多态
90+
```javascript
91+
class Cat extends Animal {
92+
speak() {
93+
console.log(`${this.name} meows.`);
94+
}
95+
}
96+
97+
const animals = [new Dog('Rex'), new Cat('Whiskers')];
98+
animals.forEach(animal => animal.speak());
99+
// Rex barks.
100+
// Whiskers meows.
101+
```
102+
103+
### 3. 函数式编程 (Functional Programming, FP)
104+
105+
函数式编程强调使用纯函数、不可变数据和函数组合,避免可变状态和副作用。
106+
107+
#### 纯函数与不可变性
108+
```javascript
109+
const add = (a, b) => a + b;
110+
111+
const numbers = [1, 2, 3];
112+
const newNumbers = numbers.map(num => num * 2);
113+
console.log(newNumbers); // [2, 4, 6]
114+
console.log(numbers); // [1, 2, 3] - 原数组不变
115+
```
116+
117+
#### 高阶函数
118+
```javascript
119+
const withLogging = fn => (...args) => {
120+
console.log(`Calling ${fn.name} with args:`, args);
121+
return fn(...args);
122+
};
123+
124+
const multiply = (a, b) => a * b;
125+
const loggedMultiply = withLogging(multiply);
126+
console.log(loggedMultiply(3, 4)); // Logs: Calling multiply with args: [3, 4], 12
127+
```
128+
129+
### 4. 反应式编程 (Reactive Programming)
130+
131+
反应式编程处理动态数据流和异步事件,常用于构建响应式UI和处理事件流。
132+
133+
#### 使用RxJS处理事件流
134+
```javascript
135+
import { fromEvent } from 'rxjs';
136+
import { throttleTime, map } from 'rxjs/operators';
137+
138+
const clicks = fromEvent(document, 'click');
139+
const positions = clicks.pipe(
140+
throttleTime(1000),
141+
map(event => ({ x: event.clientX, y: event.clientY }))
142+
);
143+
144+
positions.subscribe(position => console.log('Clicked at:', position));
145+
```
146+
147+
## 设计模式
148+
149+
### 1. 单例模式 (Singleton Pattern)
150+
单例模式确保一个类只有一个实例,并提供全局访问点。
151+
152+
```javascript
153+
class Logger {
154+
constructor() {
155+
if (Logger.instance) {
156+
return Logger.instance;
157+
}
158+
Logger.instance = this;
159+
this.logs = [];
160+
}
161+
162+
log(message) {
163+
this.logs.push(message);
164+
console.log(`LOG: ${message}`);
165+
}
166+
167+
printLogCount() {
168+
console.log(`${this.logs.length} logs`);
169+
}
170+
}
171+
172+
const logger1 = new Logger();
173+
const logger2 = new Logger();
174+
175+
logger1.log('This is the first log');
176+
logger2.log('This is the second log');
177+
logger1.printLogCount(); // 2 logs
178+
```
179+
180+
### 2. 工厂模式 (Factory Pattern)
181+
工厂模式通过定义一个接口或抽象类来创建对象,而不指定具体类。
182+
183+
```javascript
184+
class Shape {
185+
constructor(type) {
186+
this.type = type;
187+
}
188+
189+
draw() {
190+
console.log(`Drawing a ${this.type}`);
191+
}
192+
}
193+
194+
class ShapeFactory {
195+
createShape(type) {
196+
return new Shape(type);
197+
}
198+
}
199+
200+
const factory = new ShapeFactory();
201+
const circle = factory.createShape('circle');
202+
const square = factory.createShape('square');
203+
204+
circle.draw(); // Drawing a circle
205+
square.draw(); // Drawing a square
206+
```
207+
208+
### 3. 观察者模式 (Observer Pattern)
209+
观察者模式定义对象之间的一对多依赖关系,当一个对象状态改变时,所有依赖对象会收到通知并更新。
210+
211+
```javascript
212+
class Subject {
213+
constructor() {
214+
this.observers = [];
215+
}
216+
217+
addObserver(observer) {
218+
this.observers.push(observer);
219+
}
220+
221+
removeObserver(observer) {
222+
this.observers = this.observers.filter(obs => obs !== observer);
223+
}
224+
225+
notify(data) {
226+
this.observers.forEach(observer => observer.update(data));
227+
}
228+
}
229+
230+
class Observer {
231+
update(data) {
232+
console.log(`Observer received data: ${data}`);
233+
}
234+
}
235+
236+
const subject = new Subject();
237+
const observer1 = new Observer();
238+
const observer2 = new Observer();
239+
240+
subject.addObserver(observer1);
241+
subject.addObserver(observer2);
242+
subject.notify('Some data');
243+
```
244+
245+
### 4. 装饰者模式 (Decorator Pattern)
246+
装饰者模式允许向现有对象添加新功能,而不改变其结构。
247+
248+
```javascript
249+
class Coffee {
250+
cost() {
251+
return 5;
252+
}
253+
}
254+
255+
class MilkDecorator {
256+
constructor(coffee) {
257+
this.coffee = coffee;
258+
}
259+
260+
cost() {
261+
return this.coffee.cost() + 1;
262+
}
263+
}
264+
265+
class SugarDecorator {
266+
constructor(coffee) {
267+
this.coffee = coffee;
268+
}
269+
270+
cost() {
271+
return this.coffee.cost() + 0.5;
272+
}
273+
}
274+
275+
let coffee = new Coffee();
276+
coffee = new MilkDecorator(coffee);
277+
coffee = new SugarDecorator(coffee);
278+
console.log(coffee.cost()); // 6.5
279+
```
280+
## 前端中的依赖注入
281+
参考阅读[这篇文章](https://redi.wendell.fun/zh-CN/blogs/di)
282+
283+
## 总结
284+
这些编程范式和设计模式各有其独特的应用场景,理解并掌握它们能够帮助开发者编写出更高效、可维护和可扩展的代码。在实际开发中,根据具体需求选择合适的范式和模式是提升项目质量的重要一环。

0 commit comments

Comments
 (0)