美文网首页@IT·互联网
前端常用设计模式的实际应用

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

作者: jia林 | 来源:发表于2024-07-25 16:51 被阅读0次
设计模式简介

设计模式总共有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),而不需要了解具体的算法实现细节。

相关文章

  • Node.js与单例模式

    1、前端的JavaScript单例模式 单例模式是非常常用的设计模式,前端的JavaScript中单例模式代码可能...

  • JS设计模式-其他1-原型模式 & 桥接模式

    其他设计模式系列开始介绍前端不常用的设计模式有哪些设计模式? 创建性模式原型模式 结构型模式桥接模式 组合模式 ...

  • 通俗易懂的讲解一下Java的代理模式

    在我们通常的应用中,代理模式也是我们常用的设计模式之一。所谓的代理模式是指客户端并不直接调用实际的对象,而是通过调...

  • 简单常用设计模式

    今天总结一下前端常用的设计模式,都是一些简单常用的设模式。 构造函数模式: 工厂模式: 模块模式 混合模式 单例模...

  • 前端常用设计模式

    前端常见的设计模式主要有以下几种:1. 单例模式2. 工厂模式3. 策略模式4. 代理模式5. 观察者模式6. 模...

  • 前端常用设计模式

    前端常见的设计模式主要有以下几种: 单例模式 工厂模式 策略模式 代理模式 观察者模式 模块模式 构造函数模式 混...

  • 设计模式

    如何使用常用设计模式及示例(swift) 有哪些在实际 Android 项目中用到的设计模式? Android 设...

  • 前端常用的设计模式

    前言 设计模式定义:在面向对象软件设计过程中 针对特定问题的简洁而优雅的解决方案。在不同的编程语言中,对设计模式的...

  • 设计模式的实际应用(一)

    为什么要学习和使用设计模式啊?正确使用设计模式,不仅能让项目开发效率更高,也能让项目更容易维护。对于程序员来说,设...

  • 单例模式和多线程

    前言:     学过设计模式的同学都知道单例模式是23中设计模式中最简单也是实际应用中用到的最多的设计模式了,今天...

网友评论

    本文标题:前端常用设计模式的实际应用

    本文链接:https://www.haomeiwen.com/subject/qpkmhjtx.html