前端常用的几种设计模式

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
  • 7
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
1. MVC模式(Model-View-Controller) MVC模式是一种将应用程序分成三个核心部分的设计模式,分别是模型(Model)、视图(View)和控制器(Controller)。模型负责处理数据和业务逻辑,视图负责界面展示,控制器协调模型和视图之间的交互。 2. MVVM模式(Model-View-ViewModel) MVVM模式是一种基于MVC模式的设计模式,它将视图和模型之间的通信通过一个名为ViewModel的中间件实现。ViewModel负责处理视图和模型之间的数据绑定和事件处理,实现了视图和模型的解耦。 3. 单例模式(Singleton) 单例模式是一种创建型模式,它保证一个类只有一个实例,并提供全局访问点。这种模式在需要全局共享资源的情况下非常有用,比如数据库连接池、线程池等。 4. 观察者模式(Observer) 观察者模式是一种行为模式,它定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象,当主题对象状态发生改变时,它的所有观察者都会收到通知并更新自己的状态。 5. 策略模式(Strategy) 策略模式是一种行为模式,它定义了一系列算法,将每个算法都封装起来,使它们可以相互替换。这样,客户端可以在不改变代码的情况下选择不同的算法,从而实现不同的行为。 6. 工厂模式(Factory) 工厂模式是一种创建型模式,它定义了一个用于创建对象的接口,但是由子类决定要实例化的类是哪一个。这样,工厂方法让类的实例化推迟到了子类中进行,从而实现了解耦和灵活性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

**之火

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值