面试题答案
一键面试代码解耦常见方法
- 模块化:将大的程序分割成独立的模块,每个模块负责特定功能。例如在电商系统中,把用户管理、商品管理、订单管理等分别放到不同模块。
- 接口与抽象类:定义通用的接口或抽象类,让具体类去实现,这样不同模块间通过接口交互,降低耦合。比如定义商品接口,不同类型商品类实现该接口。
- 依赖注入:通过外部传入依赖对象,而不是在类内部创建,减少类与类之间的直接依赖。
依赖注入在电商购物车系统的应用
- 定义商品类
class Product
attr_reader :name, :price
def initialize(name, price)
@name = name
@price = price
end
end
- 定义购物车类,使用依赖注入
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
- 定义商品仓库类(模拟数据存储)
class ProductRepository
def initialize
@products = [
Product.new('Book', 20),
Product.new('Pen', 5)
]
end
def find(product_id)
@products[product_id]
end
end
- 使用示例
repository = ProductRepository.new
cart = ShoppingCart.new(repository)
cart.add_item(0)
puts cart.total_price
在上述代码中,ShoppingCart
类不直接创建Product
对象,而是通过ProductRepository
来获取商品,ProductRepository
通过依赖注入传入ShoppingCart
,实现了代码解耦。