返回

新年后让我们重新学习前端设计模式

前端

前端设计模式:编写更简洁、可读和可维护的代码

随着新年伊始,是时候学习一些新知识来提升你的前端开发技能了。设计模式是前端开发中不可或缺的一部分,它们可以帮助你编写出更简洁、更可读、更易于维护的代码。

在这篇文章中,我们将深入探讨一些最常用的前端设计模式,包括单例模式、工厂模式、观察者模式、策略模式、适配器模式、装饰器模式、代理模式、组合模式、MVC模式和MVVM模式。

单例模式

单例模式是一种创建对象的方式,它确保一个类只有一个实例。这对于需要全局访问的对象非常有用,例如数据库连接或缓存。

class Singleton {
  static instance;

  constructor() {
    if (Singleton.instance) {
      return Singleton.instance;
    }

    this.data = {};
    Singleton.instance = this;
  }

  setData(key, value) {
    this.data[key] = value;
  }

  getData(key) {
    return this.data[key];
  }
}

const instance1 = new Singleton();
const instance2 = new Singleton();

console.log(instance1 === instance2); // true

工厂模式

工厂模式是一种创建对象的方式,它将对象的创建过程封装在一个单独的工厂类中。这使得你可以轻松地创建不同类型的对象,而无需担心它们的具体实现细节。

class Factory {
  createProduct(type) {
    switch (type) {
      case "A":
        return new ProductA();
      case "B":
        return new ProductB();
      default:
        throw new Error("Invalid product type");
    }
  }
}

class ProductA {
  doSomething() {
    console.log("I'm product A");
  }
}

class ProductB {
  doSomething() {
    console.log("I'm product B");
  }
}

const factory = new Factory();

const productA = factory.createProduct("A");
const productB = factory.createProduct("B");

productA.doSomething(); // I'm product A
productB.doSomething(); // I'm product B

观察者模式

观察者模式是一种设计模式,它允许对象订阅其他对象的事件。当被订阅的对象发生变化时,它会通知所有订阅者,以便它们可以做出相应的反应。

class Observable {
  constructor() {
    this.subscribers = [];
  }

  subscribe(subscriber) {
    this.subscribers.push(subscriber);
  }

  notifySubscribers() {
    this.subscribers.forEach((subscriber) => subscriber.update());
  }
}

class Subscriber {
  constructor(observable) {
    this.observable = observable;
    this.observable.subscribe(this);
  }

  update() {
    console.log("Subscriber notified");
  }
}

const observable = new Observable();
const subscriber1 = new Subscriber(observable);
const subscriber2 = new Subscriber(observable);

observable.notifySubscribers(); // Subscriber notified
observable.notifySubscribers(); // Subscriber notified

策略模式

策略模式是一种设计模式,它允许你在运行时选择不同的算法或行为。这使得你可以轻松地切换不同的策略,而无需修改代码。

class Strategy {
  execute() {
    throw new Error("Not implemented");
  }
}

class ConcreteStrategyA extends Strategy {
  execute() {
    console.log("Concrete strategy A");
  }
}

class ConcreteStrategyB extends Strategy {
  execute() {
    console.log("Concrete strategy B");
  }
}

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

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

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

const context = new Context(strategyA);
context.executeStrategy(); // Concrete strategy A

context.strategy = strategyB;
context.executeStrategy(); // Concrete strategy B

适配器模式

适配器模式是一种设计模式,它允许你将一个类的接口转换为另一个类可以理解的接口。这使得你可以将不同的类协同工作,即使它们的接口不兼容。

class Adaptee {
  specificRequest() {
    console.log("Specific request");
  }
}

class Adapter {
  constructor(adaptee) {
    this.adaptee = adaptee;
  }

  request() {
    this.adaptee.specificRequest();
  }
}

class Client {
  constructor(adapter) {
    this.adapter = adapter;
  }

  makeRequest() {
    this.adapter.request();
  }
}

const adaptee = new Adaptee();
const adapter = new Adapter(adaptee);
const client = new Client(adapter);

client.makeRequest(); // Specific request

装饰器模式

装饰器模式是一种设计模式,它允许你在不改变对象本身的情况下,动态地添加或修改对象的行为。这使得你可以轻松地扩展对象的接口,而无需修改其内部状态。

class Component {
  operation() {
    console.log("Component operation");
  }
}

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

  operation() {
    this.component.operation();
    console.log("Decorator operation");
  }
}

const component = new Component();
const decorator = new Decorator(component);

decorator.operation(); // Component operation
                    // Decorator operation

代理模式

代理模式是一种设计模式,它为另一个对象提供一个替代或间接访问的方式。这可以用于控制对原始对象的访问、添加额外的功能或提供安全机制。

class Subject {
  request() {
    console.log("Subject request");
  }
}

class Proxy {
  constructor(subject) {
    this.subject = subject;
  }

  request() {
    if (this.checkAccess()) {
      this.subject.request();
    } else {
      console.log("Access denied");
    }
  }

  checkAccess() {
    // Access control logic
    return true;
  }
}

const subject = new Subject();
const proxy = new Proxy(subject);

proxy.request(); // Subject request

组合模式

组合模式是一种设计模式,它允许你将对象组合成树形结构。这使得你可以轻松地表示复杂的对象层次结构,并对其进行遍历和管理。

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

  add(component) {
    // Not implemented
  }

  remove(component) {
    // Not implemented
  }

  getChild(index) {
    // Not implemented
  }

  operation() {
    console.log(`Operation on ${this.name}`);
  }
}

class Composite extends Component {
  constructor(name) {
    super(name);
    this.children = [];
  }

  add(component) {
    this.children.push(component);
  }

  remove(component) {
    const index = this.children.indexOf(component);
    if (index !== -1) {
      this.children.splice(index, 1);
    }
  }

  getChild(index) {
    return this.children[index];
  }

  operation() {
    super.operation();
    this.children.forEach((child) => child.operation());
  }
}

const root = new Composite("Root");
const leaf1 = new Component("Leaf 1");
const leaf2 = new Component("Leaf 2");
root.add(leaf1);
root.add(leaf2);

root.operation(); // Operation on Root
              // Operation on Leaf 1
              // Operation on Leaf 2

MVC模式

MVC模式(模型-视图-控制器)是一种设计模式,它将应用程序的业务逻辑(模型)、用户界面(视图)和用户交互(控制器)分离成不同的组件。这使得应用程序更易于维护和扩展。

// Model
class Model {
  constructor() {
    this.data = [];
  }

  add(item) {
    this.data.push(item);
  }

  remove(item) {
    const index = this.data.indexOf(item);
    if (index !== -1) {
      this.data.splice(index, 1);
    }
  }

  getData() {
    return this.data;
  }
}

// View
class View {
  constructor(model) {
    this.model = model;

    this.list = document.getElementById("list");
  }

  render() {
    this.list.innerHTML =