设计模式

 TypeScript   大苹果   2024-10-06 15:55   263

设计模式在 TypeScript 中的实现

设计模式是解决软件设计中常见问题的典型方案。以下是常用和不常用的设计模式在 TypeScript 中的实现,包括它们的说明和示例代码。

1. 创建型模式

1.1 单例模式 (Singleton)

确保一个类只有一个实例,并提供全局访问点。

class Singleton {
    private static instance: Singleton;

    private constructor() {}

    public static getInstance(): Singleton {
        if (!Singleton.instance) {
            Singleton.instance = new Singleton();
        }
        return Singleton.instance;
    }
}

// 使用示例
const singleton1 = Singleton.getInstance();
const singleton2 = Singleton.getInstance();
console.log(singleton1 === singleton2); // true
1.2 工厂模式 (Factory Method)

定义一个创建对象的接口,但由子类决定实例化哪个类。

interface Product {
    operation(): string;
}

class ConcreteProductA implements Product {
    public operation(): string {
        return 'Result of ConcreteProductA';
    }
}

class ConcreteProductB implements Product {
    public operation(): string {
        return 'Result of ConcreteProductB';
    }
}

abstract class Creator {
    public abstract factoryMethod(): Product;

    public someOperation(): string {
        const product = this.factoryMethod();
        return `Creator: The same creator's code has just worked with ${product.operation()}`;
    }
}

class ConcreteCreatorA extends Creator {
    public factoryMethod(): Product {
        return new ConcreteProductA();
    }
}

class ConcreteCreatorB extends Creator {
    public factoryMethod(): Product {
        return new ConcreteProductB();
    }
}

// 使用示例
const creatorA = new ConcreteCreatorA();
console.log(creatorA.someOperation()); // "Creator: The same creator's code has just worked with Result of ConcreteProductA"
1.3 抽象工厂模式 (Abstract Factory)

提供一个接口,用于创建相关或依赖对象的家族,而无需明确指定具体类。

interface ProductA {
    operationA(): string;
}

interface ProductB {
    operationB(): string;
}

class ConcreteProductA1 implements ProductA {
    public operationA(): string {
        return 'Result of ConcreteProductA1';
    }
}

class ConcreteProductB1 implements ProductB {
    public operationB(): string {
        return 'Result of ConcreteProductB1';
    }
}

interface AbstractFactory {
    createProductA(): ProductA;
    createProductB(): ProductB;
}

class ConcreteFactory1 implements AbstractFactory {
    public createProductA(): ProductA {
        return new ConcreteProductA1();
    }

    public createProductB(): ProductB {
        return new ConcreteProductB1();
    }
}

// 使用示例
const factory = new ConcreteFactory1();
const productA = factory.createProductA();
const productB = factory.createProductB();
console.log(productA.operationA()); // "Result of ConcreteProductA1"
console.log(productB.operationB()); // "Result of ConcreteProductB1"

2. 结构型模式

2.1 适配器模式 (Adapter)

将一个类的接口转换成客户端所期望的另一种接口。

class Target {
    public request(): string {
        return 'Target: The default target\'s behavior.';
    }
}

class Adaptee {
    public specificRequest(): string {
        return 'Adaptee: The specific behavior.';
    }
}

class Adapter extends Target {
    private adaptee: Adaptee;

    constructor(adaptee: Adaptee) {
        super();
        this.adaptee = adaptee;
    }

    public request(): string {
        return `Adapter: (TRANSLATED) ${this.adaptee.specificRequest()}`;
    }
}

// 使用示例
const adaptee = new Adaptee();
const adapter = new Adapter(adaptee);
console.log(adapter.request()); // "Adapter: (TRANSLATED) Adaptee: The specific behavior."
2.2 装饰者模式 (Decorator)

动态地给一个对象添加一些额外的职责。

interface Component {
    operation(): string;
}

class ConcreteComponent implements Component {
    public operation(): string {
        return 'ConcreteComponent';
    }
}

class Decorator implements Component {
    protected component: Component;

    constructor(component: Component) {
        this.component = component;
    }

    public operation(): string {
        return this.component.operation();
    }
}

class ConcreteDecoratorA extends Decorator {
    public operation(): string {
        return `ConcreteDecoratorA(${super.operation()})`;
    }
}

// 使用示例
const simple = new ConcreteComponent();
console.log(simple.operation()); // "ConcreteComponent"

const decorated = new ConcreteDecoratorA(simple);
console.log(decorated.operation()); // "ConcreteDecoratorA(ConcreteComponent)"

3. 行为型模式

3.1 策略模式 (Strategy)

定义一系列算法,将它们一个个封装起来,并使它们可以互相替换。

interface Strategy {
    doAlgorithm(data: string[]): string[];
}

class ConcreteStrategyA implements Strategy {
    public doAlgorithm(data: string[]): string[] {
        return data.sort();
    }
}

class ConcreteStrategyB implements Strategy {
    public doAlgorithm(data: string[]): string[] {
        return data.reverse();
    }
}

class Context {
    private strategy: Strategy;

    constructor(strategy: Strategy) {
        this.strategy = strategy;
    }

    public setStrategy(strategy: Strategy): void {
        this.strategy = strategy;
    }

    public doSomeBusinessLogic(): void {
        const result = this.strategy.doAlgorithm(['a', 'b', 'c']);
        console.log(result);
    }
}

// 使用示例
const context = new Context(new ConcreteStrategyA());
context.doSomeBusinessLogic(); // ["a", "b", "c"]

context.setStrategy(new ConcreteStrategyB());
context.doSomeBusinessLogic(); // ["c", "b", "a"]
3.2 观察者模式 (Observer)

定义对象间的一种一对多依赖关系,以便当一个对象状态改变时,所有依赖于它的对象都得到通知并自动更新。

interface Observer {
    update(subject: Subject): void;
}

interface Subject {
    attach(observer: Observer): void;
    detach(observer: Observer): void;
    notify(): void;
}

class ConcreteSubject implements Subject {
    private observers: Observer[] = [];
    private state: number;

    public attach(observer: Observer): void {
        this.observers.push(observer);
    }

    public detach(observer: Observer): void {
        const index = this.observers.indexOf(observer);
        this.observers.splice(index, 1);
    }

    public notify(): void {
        for (const observer of this.observers) {
            observer.update(this);
        }
    }

    public getState(): number {
        return this.state;
    }

    public setState(state: number): void {
        this.state = state;
        this.notify();
    }
}

class ConcreteObserverA implements Observer {
    public update(subject: Subject): void {
        console.log(`ConcreteObserverA: Reacted to the event. New state: ${subject.getState()}`);
    }
}

// 使用示例
const subject = new ConcreteSubject();
const observerA = new ConcreteObserverA();
subject.attach(observerA);
subject.setState(1); // "ConcreteObserverA: Reacted to the event. New state: 1"

不常用设计模式

4.1 责任链模式 (Chain of Responsibility)

通过将请求的发送者和接收者解耦,形成一条处理请求的责任链。

abstract class Handler {
    protected successor: Handler;

    public setSuccessor(successor: Handler): void {
        this.successor = successor;
    }

    public abstract handleRequest(request: number): void;
}

class ConcreteHandlerA extends Handler {
    public handleRequest(request: number): void {
        if (request < 10) {
            console.log(`Handler A handled request ${request}`);
        } else if (this.successor) {
            this.successor.handleRequest(request);
        }
    }
}

class ConcreteHandlerB extends Handler {
    public handleRequest(request: number): void {
        if (request < 20) {
            console.log(`Handler B handled request ${request}`);
        } else if (this.successor) {
            this.successor.handleRequest(request);
        }
    }
}

// 使用示例
const handlerA = new ConcreteHandlerA();
const handlerB = new ConcreteHandlerB();
handlerA.setSuccessor(handlerB);

handlerA.handleRequest(5);  // "Handler A handled request 5"
handlerA.handleRequest(15); // "Handler B handled request 15"
4.2 状态模式 (State)

允许对象在内部状态改变时改变其行为。

interface State {
    handle(context: Context): void;
}

class ConcreteStateA implements State {
    public handle(context: Context): void {
        console.log('Handling request in State A');
        context.setState(new ConcreteStateB());
    }
}

class ConcreteStateB implements State {
    public handle(context: Context): void {
        console.log('Handling request in State B');
        context.setState(new ConcreteStateA());
    }
}

class Context {
    private state: State;

    constructor(state: State) {
        this.setState(state);
    }

    public setState(state: State): void {
        this.state = state;
    }

    public request(): void {
        this.state.handle(this);
    }
}

// 使用示例
const context = new Context(new ConcreteStateA());
context.request

(); // "Handling request in State A"
context.request(); // "Handling request in State B"

总结

以上展示了多种设计模式在 TypeScript 中的实现,包括常用和不常用的模式。这些模式为代码的组织和结构提供了灵活性,增强了可维护性和可扩展性。掌握这些设计模式,可以帮助开发者在实际开发中更好地解决问题,提高代码质量。