前端常用的几种设计模式

1. 模块模式(Module Pattern)

模块模式用于封装代码,创建私有变量和方法,同时提供公共接口。

const myModule = (function() {
    var privateVar = 'I am private';

    function privateMethod() {
        console.log('This is a private method');
    }

    return {
        publicMethod: function() {
            console.log('This is a public method');
        },
        getPrivateVar: function() {
            return privateVar;
        }
    };
})();

console.log(myModule.getPrivateVar()); // 输出: I am private
myModule.publicMethod(); // 输出: This is a public method

2. 单例模式(Singleton Pattern)

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

class Logger {
    static instance = null;

    static getInstance() {
        if (!this.instance) {
            this.instance = new Logger();
        }
        return this.instance;
    }

    log(message) {
        console.log(message);
    }
}

const logger1 = Logger.getInstance();
const logger2 = Logger.getInstance();

logger1.log('This is a log message'); // 输出: This is a log message
console.log(logger1 === logger2); // 输出: true

3. 工厂模式(Factory Pattern)

工厂模式用于创建对象,将对象创建的逻辑封装起来。

class Rectangle {
    constructor(width, height) {
        this.width = width;
        this.height = height;
    }

    area() {
        return this.width * this.height;
    }
}

class Square {
    constructor(side) {
        this.side = side;
    }

    area() {
        return this.side * this.side;
    }
}

class ShapeFactory {
    static createShape(shapeType, dimension) {
        if (shapeType === 'rectangle') {
            return new Rectangle(dimension.width, dimension.height);
        } else if (shapeType === 'square') {
            return new Square(dimension.side);
        }
    }
}

const shape1 = ShapeFactory.createShape('rectangle', { width: 5, height: 10 });
const shape2 = ShapeFactory.createShape('square', { side: 5 });

console.log(shape1.area()); // 输出: 50
console.log(shape2.area()); // 输出: 25

4. 观察者模式(Observer Pattern)

观察者模式定义了对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知。

class Subject {
    constructor() {
        this.observers = [];
    }

    attach(observer) {
        this.observers.push(observer);
    }

    notify(message) {
        this.observers.forEach(observer => observer.update(message));
    }
}

class Observer {
    constructor(name) {
        this.name = name;
    }

    update(message) {
        console.log(`${this.name} received message: ${message}`);
    }
}

const subject = new Subject();
const observer1 = new Observer('Observer 1');
const observer2 = new Observer('Observer 2');

subject.attach(observer1);
subject.attach(observer2);

subject.notify('Hello, Observers!'); // 输出: Observer 1 received message: Hello, Observers! Observer 2 received message: Hello, Observers!

5. 策略模式(Strategy Pattern)

策略模式定义了一系列算法,并将每一个算法封装起来,使它们可以互换。

class Strategy {
    execute() {
        throw new Error('Strategy must be implemented');
    }
}

class ConcreteStrategyA extends Strategy {
    execute() {
        console.log('Executing Concrete Strategy A');
    }
}

class ConcreteStrategyB extends Strategy {
    execute() {
        console.log('Executing Concrete Strategy B');
    }
}

class Context {
    constructor(strategy) {
        this.strategy = strategy;
    }

    setStrategy(strategy) {
        this.strategy = strategy;
    }

    executeStrategy() {
        this.strategy.execute();
    }
}

const strategyA = new ConcreteStrategyA();
const strategyB = new ConcreteStrategyB();
const context = new Context(strategyA);

context.executeStrategy(); // 输出: Executing Concrete Strategy A

context.setStrategy(strategyB);
context.executeStrategy(); // 输出: Executing Concrete Strategy B

6. 装饰器模式(Decorator Pattern)

装饰器模式允许用户在不改变对象自身的基础上,向一个对象添加新的功能。

class Component {
    operation() {
        return 'Basic Operation';
    }
}

class Decorator extends Component {
    constructor(component) {
        super();
        this.component = component;
    }

    operation() {
        return `${this.component.operation()} + Decorator's behavior`;
    }
}

const component = new Component();
console.log(component.operation()); // 输出: Basic Operation

const decoratedComponent = new Decorator(component);
console.log(decoratedComponent.operation()); // 输出: Basic Operation + Decorator's behavior

你可能感兴趣的:(设计模式,前端,设计模式,javascript)