@IT·互联网

前端常用设计模式的实际应用

2024-07-25  本文已影响0人  jia林
设计模式简介

设计模式总共有23种。其目的是在代码封装性、可读性、重用性、可扩展性、可靠性等方面,使项目更易于开发、维护及扩展。可以分为三大类,创建型模式、结构型模式、行为型模式。

  1. 创建型模式:创建对象的同时隐藏创建逻辑的方式

2.结构型模式:关注类和对象的组合,简化系统设计

3.行为型模式:关注对象之间的通信,增加灵活性

实际场景应用
// 定义普通按钮组件
class Button {
  constructor(props) {
    this.props = props;
  }

  render() {
    const button = document.createElement('button');
    button.innerText = this.props.text;
    button.classList.add('btn');
    return button;
  }
}

// 定义主要按钮组件
class PrimaryButton extends Button {
  render() {
    const button = super.render();
    button.classList.add('btn-primary');
    return button;
  }
}

// 定义警告按钮组件
class WarningButton extends Button {
  render() {
    const button = super.render();
    button.classList.add('btn-warning');
    return button;
  }
}

// 按钮工厂函数,根据类型创建相应的按钮实例
function ButtonFactory(type, props) {
  switch (type) {
    case 'primary':
      return new PrimaryButton(props);
    case 'warning':
      return new WarningButton(props);
    default:
      return new Button(props);
  }
}

// 使用工厂模式创建按钮实例
const button1 = ButtonFactory('primary', { text: 'Primary Button' });
const button2 = ButtonFactory('warning', { text: 'Warning Button' });
const button3 = ButtonFactory('normal', { text: 'Normal Button' });

// 在页面上插入按钮
document.body.appendChild(button1.render());
document.body.appendChild(button2.render());
document.body.appendChild(button3.render());
// 通过工厂模式我们可以将创建对象的逻辑封装起来,使得调用方只需要关心需要哪种类型的按钮,而不需要了解每个按钮类型的具体实现细节。
// 登录管理器
class LoginManager {
  constructor() {
    if (LoginManager.instance) {
      return LoginManager.instance;
    }
    this.isLoggedIn = false;
    LoginManager.instance = this;
  }

  login(username, password) {
    // 登录的逻辑
    this.isLoggedIn = true;
  }

  logout() {
    // 登出的逻辑
    this.isLoggedIn = false;
  }
}

const loginManager = new LoginManager();
// 无论在项目的何处获取 LoginManager 的实例,都始终是同一个,确保了登录状态的唯一性和一致性。

在实现懒加载(Lazy Loading)、预加载(Preloading)等功能时,可以使用代理模式。代理对象可以控制对原始对象的访问,并在需要时加载或处理数据。

// 代理加载图片类,若缓存中有,则直接返回缓存数据;若没有,则调用加载图片类
class Image {
  constructor(url) {
    this.url = url
    this.loadImage()
  }
  loadImage() {
    console.log(`加载图片 ${this.url}`)
  }
}

class ProxyImage {
  constructor(url) {
    this.url = url
  }
  loadImage() {
    if (!this.image) {
      this.image = new Image(this.url)
    }
    console.log(`缓存中图片 ${this.url}`)
  }
}
const image1 = new Image('image1.jpg')
const proxyImage1 = new ProxyImage('image1.jpg')

proxyImage1.loadImage(); // 加载图片
proxyImage1.loadImage(); // 缓存中图片
//应用外观模式封装一个统一的 DOM 元素事件绑定/取消方法,用于兼容不同版本的浏览器和更方便的调用


// 绑定事件
function addEvent(element, event, handler) {
  if (element.addEventListener) {
    element.addEventListener(event, handler, false)
  } else if (element.attachEvent) {
    element.attachEvent("on" + event, handler)
  } else {
    element["on" + event] = fn
  }
}

// 取消绑定
function removeEvent(element, event, handler) {
  if (element.removeEventListener) {
    element.removeEventListener(event, handler, false)
  } else if (element.detachEvent) {
    element.detachEvent("on" + event, handler)
  } else {
    element["on" + event] = null
  }
}
// 定义不同的支付策略
class PaymentStrategy {
  constructor() {
    this.paymentMethod = null;
  }

  setPaymentMethod(paymentMethod) {
    this.paymentMethod = paymentMethod;
  }

  calculatePayment(orderTotal) {
    return this.paymentMethod.calculate(orderTotal);
  }
}

// 定义支付方式:信用卡支付
class CreditCardPayment {
  calculate(orderTotal) {
    // 假设信用卡支付有 2% 的手续费
    const fee = orderTotal * 0.02;
    return orderTotal + fee;
  }
}

// 定义支付方式:PayPal 支付
class PayPalPayment {
  calculate(orderTotal) {
    // PayPal 支付没有额外费用
    return orderTotal;
  }
}

// 使用策略模式处理订单支付
const orderTotal = 100; // 订单总额为 100 美元

const paymentStrategy = new PaymentStrategy();

// 选择信用卡支付方式
paymentStrategy.setPaymentMethod(new CreditCardPayment());
const totalWithCreditCard = paymentStrategy.calculatePayment(orderTotal);
console.log('Total with Credit Card:', totalWithCreditCard);

// 选择 PayPal 支付方式
paymentStrategy.setPaymentMethod(new PayPalPayment());
const totalWithPayPal = paymentStrategy.calculatePayment(orderTotal);
console.log('Total with PayPal:', totalWithPayPal);

// PaymentStrategy 类是策略模式的上下文,它包含一个当前支付方法的引用,并提供了一个方法 calculatePayment 来执行具体的支付计算。
// CreditCardPayment 和 PayPalPayment 类是具体的支付策略,分别实现了 calculate 方法来计算订单总额。
// 在使用过程中,我们首先创建了一个 PaymentStrategy 实例,然后根据用户的选择设置不同的支付方式,并调用 calculatePayment 方法来获取最终支付金额。
//策略模式的优势在于它使得算法的选择和使用算法的客户端分离开来,客户端只需知道如何使用策略模式的上下文(PaymentStrategy),而不需要了解具体的算法实现细节。
上一篇 下一篇

猜你喜欢

热点阅读