设计模式可视化演示

点击按钮查看每种设计模式的动态演示

单例模式 (Singleton)

确保一个类只有一个实例,并提供一个全局访问点。适用于:数据库连接、配置管理器、日志记录器等只需要一个实例的对象。

动态演示

实例 A
实例 B

代码示例

// 单例模式实现
class Singleton {
    private static instance: Singleton;
    
    private constructor() {}
    
    public static getInstance(): Singleton {
        if (!Singleton.instance) {
            Singleton.instance = new Singleton();
        }
        return Singleton.instance;
    }
}

// 测试:两次获取的是否为同一实例
const a = Singleton.getInstance();
const b = Singleton.getInstance();
console.log(a === b); // true

工厂模式 (Factory)

定义一个创建对象的接口,让子类决定实例化哪个类。工厂方法使一个类的实例化延迟到其子类。适用于:对象创建逻辑复杂、需要根据条件创建不同类型对象。

动态演示

轿车
卡车
巴士

代码示例

// 工厂模式实现
interface Vehicle {
    drive(): void;
}

class Car implements Vehicle {
    drive() {
        console.log('轿车在行驶');
    }
}

class Truck implements Vehicle {
    drive() {
        console.log('卡车在运输');
    }
}

// 工厂
class VehicleFactory {
    createVehicle(type: string): Vehicle {
        switch(type) {
            case 'car': return new Car();
            case 'truck': return new Truck();
            default: throw new Error('未知类型');
        }
    }
}

观察者模式 (Observer)

定义对象间的一种一对多依赖关系,当一个对象状态改变时,所有依赖它的对象都会收到通知并自动更新。适用于:事件系统、消息推送、GUI响应式编程。

动态演示

发布者

代码示例

// 观察者模式实现
interface Observer {
    update(state: any): void;
}

class Subject {
    private observers: Observer[] = [];
    
    attach(observer: Observer) {
        this.observers.push(observer);
    }
    
    notify(state: any) {
        this.observers.forEach(o => 
            o.update(state)
        );
    }
}

应用场景

// 实际应用:Vue 响应式原理
class ReactiveData extends Subject {
    private _value: any;
    
    get value() {
        return this._value;
    }
    
    set value(val: any) {
        this._value = val;
        this.notify(val); // 自动通知
    }
}

const data = new ReactiveData();
data.attach({ update: (v) => console.log(v) });
data.value = 'hello'; // 自动触发更新

装饰器模式 (Decorator)

动态地给对象添加一些额外的职责,比继承更灵活。适用于:功能扩展、类库扩展、日志记录、权限控制等。

动态演示

基础组件
权限装饰
日志装饰
增强组件

代码示例

// 装饰器模式实现
interface Component {
    operation(): string;
}

class ConcreteComponent implements Component {
    operation() {
        return '基础功能';
    }
}

class Decorator implements Component {
    constructor(protected component: Component) {}
    
    operation() {
        return this.component.operation();
    }
}

class LoggingDecorator extends Decorator {
    operation() {
        console.log('日志:开始操作');
        return super.operation();
    }
}

应用场景

// Node.js 装饰器示例
@logged
@authenticated
@cached
async function fetchUser(id: string) {
    return await db.find(id);
}

// Python 装饰器示例
@retry(max_attempts=3)
@timeout(seconds=30)
def api_call():
    return requests.get(url)

策略模式 (Strategy)

定义一系列算法,把它们一个个封装起来,并且使它们可以相互替换。适用于:多种支付方式、多种排序算法、多种认证方式等。

动态演示

上下文
支付宝
微信支付
银行卡

代码示例

// 策略模式实现
interface PaymentStrategy {
    pay(amount: number): void;
}

class Alipay implements PaymentStrategy {
    pay(amount) {
        console.log(`使用支付宝支付 ¥${amount}`);
    }
}

class WeChatPay implements PaymentStrategy {
    pay(amount) {
        console.log(`使用微信支付 ¥${amount}`);
    }
}

class ShoppingCart {
    setStrategy(strategy: PaymentStrategy) {
        this.strategy = strategy;
    }
    
    checkout(amount) {
        this.strategy.pay(amount);
    }
}

实际应用

// React 中的策略模式
const strategies = {
    'bold': (text) => `**${text}**`,
    'italic': (text) => `*${text}*`,
    'code': (text) => `` `${text}` ``,
};

function formatText(text, strategy) {
    return strategies[strategy]?.(text) ?? text;
}

formatText('hello', 'bold'); // **hello**
formatText('world', 'code'); // `world`

适配器模式 (Adapter)

将一个类的接口转换成客户期望的另一个接口,使原本不兼容的类可以合作。适用于:集成第三方库、兼容新旧系统、接口转换。

动态演示

旧系统
适配器
新接口

代码示例

// 适配器模式实现
// 目标接口(新系统期望的)
interface Target {
    request(): string;
}

// 需要适配的类(旧系统)
class Adaptee {
    specificRequest() {
        return '旧系统数据';
    }
}

// 适配器
class Adapter implements Target {
    constructor(private adaptee: Adaptee) {}
    
    request() {
        const result = this.adaptee.specificRequest();
        return `适配转换: ${result}`;
    }
}

实际应用

// 实际案例:适配第三方支付 SDK
interface PaymentGateway {
    pay(amount: number): Promise<boolean>;
}

// 适配旧的 Stripe SDK
class StripeAdapter implements PaymentGateway {
    constructor(private stripe: OldStripe) {}
    
    async pay(amount) {
        // 转换接口格式
        return await this.stripe.charge({
            amount: amount * 100, // 分转元
            currency: 'cny'
        });
    }
}