name: 代码模式 description: 常用代码模式和最佳实践快速参考
代码模式参考
常用模式的快速参考。请将其作为起点,而非严格的模板。
创建型模式
工厂模式
// 适用场景:创建对象时无需指定具体类
interface Product { use(): void }
class ConcreteProductA implements Product {
use() { console.log('使用 A') }
}
class ProductFactory {
static create(type: string): Product {
const products = { a: ConcreteProductA };
return new products[type]();
}
}
建造者模式
// 适用场景:具有多个可选参数的复杂对象构建
class QueryBuilder {
private query = { select: '*', from: '', where: [] };
select(fields: string) { this.query.select = fields; return this; }
from(table: string) { this.query.from = table; return this; }
where(condition: string) { this.query.where.push(condition); return this; }
build() { return this.query; }
}
// 用法示例
const query = new QueryBuilder()
.select('name, email')
.from('users')
.where('active = true')
.build();
单例模式
// 适用场景:只需要一个实例(谨慎使用!)
class Database {
private static instance: Database;
private constructor() {}
static getInstance(): Database {
if (!Database.instance) {
Database.instance = new Database();
}
return Database.instance;
}
}
结构型模式
适配器模式
// 适用场景:让不兼容的接口协同工作
interface ModernLogger { log(msg: string): void }
class LegacyLogger {
writeLog(message: string, level: number) { /* ... */ }
}
class LoggerAdapter implements ModernLogger {
constructor(private legacy: LegacyLogger) {}
log(msg: string) { this.legacy.writeLog(msg, 1); }
}
装饰器模式
// 适用场景:在不修改原始对象的情况下添加行为
interface Coffee { cost(): number; description(): string }
class SimpleCoffee implements Coffee {
cost() { return 5; }
description() { return '咖啡'; }
}
class MilkDecorator implements Coffee {
constructor(private coffee: Coffee) {}
cost() { return this.coffee.cost() + 2; }
description() { return this.coffee.description() + ' + 牛奶'; }
}
行为型模式
策略模式
// 适用场景:算法需要在运行时选择
interface PaymentStrategy {
pay(amount: number): void;
}
class CreditCardPayment implements PaymentStrategy {
pay(amount: number) { console.log(`通过信用卡支付 ${amount}`); }
}
class PayPalPayment implements PaymentStrategy {
pay(amount: number) { console.log(`通过 PayPal 支付 ${amount}`); }
}
class Checkout {
constructor(private strategy: PaymentStrategy) {}
process(amount: number) { this.strategy.pay(amount); }
}
观察者模式
// 适用场景:对象需要被通知状态变化
type Listener<T> = (data: T) => void;
class EventEmitter<T> {
private listeners: Listener<T>[] = [];
subscribe(listener: Listener<T>) {
this.listeners.push(listener);
return () => this.listeners = this.listeners.filter(l => l !== listener);
}
emit(data: T) {
this.listeners.forEach(l => l(data));
}
}
错误处理模式
结果类型
// 适用场景:错误是预期内的,而非异常情况
type Result<T, E = Error> =
| { ok: true; value: T }
| { ok: false; error: E };
function divide(a: number, b: number): Result<number, string> {
if (b === 0) return { ok: false, error: '除以零' };
return { ok: true, value: a / b };
}
const result = divide(10, 2);
if (result.ok) {
console.log(result.value); // 5
} else {
console.error(result.error);
}
退避重试
// 适用场景:预期会出现暂时性故障
async function retry<T>(
fn: () => Promise<T>,
attempts = 3,
delay = 1000
): Promise<T> {
for (let i = 0; i < attempts; i++) {
try {
return await fn();
} catch (e) {
if (i === attempts - 1) throw e;
await new Promise(r => setTimeout(r, delay * Math.pow(2, i)));
}
}
throw new Error('无法到达');
}
异步模式
承诺队列
// 适用场景:限制并发异步操作
class PromiseQueue {
private queue: (() => Promise<any>)[] = [];
private running = 0;
constructor(private concurrency: number) {}
add<T>(fn: () => Promise<T>): Promise<T> {
return new Promise((resolve, reject) => {
this.queue.push(async () => {
try { resolve(await fn()); }
catch (e) { reject(e); }
});
this.process();
});
}
private async process() {
if (this.running >= this.concurrency || !this.queue.length) return;
this.running++;
await this.queue.shift()!();
this.running--;
this.process();
}
}
防抖
// 适用场景:限制快速连续的函数调用
function debounce<T extends (...args: any[]) => any>(
fn: T,
delay: number
): (...args: Parameters<T>) => void {
let timeout: NodeJS.Timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => fn(...args), delay);
};
}
数据模式
仓储模式
// 适用场景:抽象数据访问
interface Repository<T> {
findById(id: string): Promise<T | null>;
findAll(): Promise<T[]>;
save(entity: T): Promise<T>;
delete(id: string): Promise<void>;
}
class UserRepository implements Repository<User> {
constructor(private db: Database) {}
async findById(id: string) {
return this.db.query('SELECT * FROM users WHERE id = ?', [id]);
}
// ... 其他方法
}
工作单元
// 适用场景:协调多个仓储的写入操作
class UnitOfWork {
private operations: (() => Promise<void>)[] = [];
register(operation: () => Promise<void>) {
this.operations.push(operation);
}
async commit() {
await this.db.beginTransaction();
try {
for (const op of this.operations) await op();
await this.db.commit();
} catch (e) {
await this.db.rollback();
throw e;
}
}
}
何时使用每种模式
| 问题 | 模式 |
|---|---|
| 复杂对象创建 | 建造者模式 |
| 多个相似对象 | 工厂模式 |
| 全局状态(谨慎!) | 单例模式 |
| 不兼容接口 | 适配器模式 |
| 动态添加功能 | 装饰器模式 |
| 可交换算法 | 策略模式 |
| 基于事件的通信 | 观察者模式 |
| 预期故障 | 结果类型 |
| 暂时性故障 | 退避重试 |
| 速率限制 | 防抖/节流 |
| 数据访问抽象 | 仓储模式 |
| 事务一致性 | 工作单元 |