MST
星途 面试题库

面试题:JavaScript 闭包模块在复杂业务逻辑下的类对象设计

假设你正在开发一个电商系统,有商品管理、购物车、订单处理等复杂业务模块,需要使用基于类对象和闭包模块的方式进行代码组织。请描述你的设计思路,包括如何划分类对象,以及闭包模块在各模块间数据交互和状态管理中的应用。
34.6万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试

类对象划分

  1. 商品管理模块
    • 商品类(Product):用于表示单个商品,包含商品的基本信息如ID、名称、价格、描述、库存等属性,以及一些操作方法,比如获取商品详情、更新库存等。例如:
class Product:
    def __init__(self, product_id, name, price, description, stock):
        self.product_id = product_id
        self.name = name
        self.price = price
        self.description = description
        self.stock = stock

    def get_product_detail(self):
        return f"商品名称: {self.name}, 价格: {self.price}, 描述: {self.description}, 库存: {self.stock}"

    def update_stock(self, new_stock):
        self.stock = new_stock
- **商品管理类(ProductManager)**:负责管理商品的增删改查等操作。它可以包含一个商品列表属性,以及添加商品、删除商品、查询商品等方法。例如:
class ProductManager:
    def __init__(self):
        self.products = []

    def add_product(self, product):
        self.products.append(product)

    def delete_product(self, product_id):
        self.products = [p for p in self.products if p.product_id != product_id]

    def get_product_by_id(self, product_id):
        for product in self.products:
            if product.product_id == product_id:
                return product
        return None
  1. 购物车模块
    • 购物车项类(CartItem):表示购物车中的一项商品,包含商品对象和购买数量属性。例如:
class CartItem:
    def __init__(self, product, quantity):
        self.product = product
        self.quantity = quantity

    def get_total_price(self):
        return self.product.price * self.quantity
- **购物车类(Cart)**:管理购物车中的所有商品项,包含添加商品到购物车、从购物车移除商品、计算购物车总价等方法。例如:
class Cart:
    def __init__(self):
        self.cart_items = []

    def add_item(self, product, quantity=1):
        for item in self.cart_items:
            if item.product.product_id == product.product_id:
                item.quantity += quantity
                return
        new_item = CartItem(product, quantity)
        self.cart_items.append(new_item)

    def remove_item(self, product_id):
        self.cart_items = [item for item in self.cart_items if item.product.product_id != product_id]

    def calculate_total(self):
        total = 0
        for item in self.cart_items:
            total += item.get_total_price()
        return total
  1. 订单处理模块
    • 订单类(Order):表示一个订单,包含订单ID、用户信息(假设这里简化为用户ID)、订单状态、订单中的商品项(可以使用购物车项类似的结构)等属性,以及订单支付、订单发货等方法。例如:
class Order:
    def __init__(self, order_id, user_id, order_status="未支付"):
        self.order_id = order_id
        self.user_id = user_id
        self.order_status = order_status
        self.order_items = []

    def add_order_item(self, product, quantity):
        new_item = CartItem(product, quantity)
        self.order_items.append(new_item)

    def pay_order(self):
        if self.order_status == "未支付":
            self.order_status = "已支付"
        else:
            print("该订单已支付或状态异常")

    def ship_order(self):
        if self.order_status == "已支付":
            self.order_status = "已发货"
        else:
            print("订单未支付或状态异常,无法发货")
- **订单管理类(OrderManager)**:负责管理订单的创建、查询、更新等操作。例如:
class OrderManager:
    def __init__(self):
        self.orders = []

    def create_order(self, user_id):
        order_id = len(self.orders) + 1
        new_order = Order(order_id, user_id)
        self.orders.append(new_order)
        return new_order

    def get_order_by_id(self, order_id):
        for order in self.orders:
            if order.order_id == order_id:
                return order
        return None

闭包模块在数据交互和状态管理中的应用

  1. 数据交互
    • 在电商系统中,不同模块之间可能需要共享一些数据。例如,购物车模块可能需要获取商品管理模块中的商品信息来计算总价等。可以使用闭包来封装这些数据获取逻辑。假设我们有一个闭包函数用于获取商品价格:
def get_product_price_closure(product_manager):
    def get_product_price(product_id):
        product = product_manager.get_product_by_id(product_id)
        if product:
            return product.price
        return None
    return get_product_price

# 使用示例
pm = ProductManager()
# 添加一些商品
product1 = Product(1, "商品1", 100, "描述1", 10)
pm.add_product(product1)
get_price = get_product_price_closure(pm)
price = get_price(1)
print(price)  # 输出 100
- 这样购物车模块在计算商品总价时,通过闭包函数可以方便地获取商品价格,而不需要直接访问商品管理模块的内部结构,降低了模块间的耦合度。

2. 状态管理 - 以订单状态管理为例,订单状态的变化需要遵循一定的规则。可以使用闭包来封装订单状态转换的逻辑。例如:

def order_status_transition_closure(order_manager):
    def transition_order_status(order_id, new_status):
        order = order_manager.get_order_by_id(order_id)
        if order:
            # 这里可以添加状态转换的合法性检查
            if (new_status == "已支付" and order.order_status == "未支付") or \
               (new_status == "已发货" and order.order_status == "已支付"):
                order.order_status = new_status
                return True
            else:
                print("状态转换不合法")
                return False
        return False
    return transition_order_status

# 使用示例
om = OrderManager()
order = om.create_order(1)
transition_status = order_status_transition_closure(om)
result = transition_status(order.order_id, "已支付")
print(result)  # 输出 True
- 通过闭包,将订单状态转换的复杂逻辑封装起来,使得外部调用者只需要关心传入订单ID和新状态,而不需要了解具体的状态转换规则和订单管理的内部实现,提高了代码的可维护性和安全性。同时,闭包中可以缓存一些与订单状态管理相关的数据,提高状态管理的效率。