MST
星途 面试题库

面试题:Ruby中如何实现简单的代码解耦并举例说明依赖注入

在Ruby中,简述代码解耦的常见方法,并通过一个实际场景(例如一个简单的电商购物车系统,涉及商品、购物车等类),展示如何使用依赖注入技术来实现代码解耦,需写出关键代码。
11.0万 热度难度
编程语言Ruby

知识考点

AI 面试

面试题答案

一键面试

代码解耦常见方法

  1. 模块化:将大的程序分割成独立的模块,每个模块负责特定功能。例如在电商系统中,把用户管理、商品管理、订单管理等分别放到不同模块。
  2. 接口与抽象类:定义通用的接口或抽象类,让具体类去实现,这样不同模块间通过接口交互,降低耦合。比如定义商品接口,不同类型商品类实现该接口。
  3. 依赖注入:通过外部传入依赖对象,而不是在类内部创建,减少类与类之间的直接依赖。

依赖注入在电商购物车系统的应用

  1. 定义商品类
class Product
  attr_reader :name, :price
  def initialize(name, price)
    @name = name
    @price = price
  end
end
  1. 定义购物车类,使用依赖注入
class ShoppingCart
  def initialize(product_repository)
    @product_repository = product_repository
    @items = []
  end

  def add_item(product_id)
    product = @product_repository.find(product_id)
    @items << product if product
  end

  def total_price
    @items.sum(&:price)
  end
end
  1. 定义商品仓库类(模拟数据存储)
class ProductRepository
  def initialize
    @products = [
      Product.new('Book', 20),
      Product.new('Pen', 5)
    ]
  end

  def find(product_id)
    @products[product_id]
  end
end
  1. 使用示例
repository = ProductRepository.new
cart = ShoppingCart.new(repository)
cart.add_item(0)
puts cart.total_price

在上述代码中,ShoppingCart类不直接创建Product对象,而是通过ProductRepository来获取商品,ProductRepository通过依赖注入传入ShoppingCart,实现了代码解耦。