MST

星途 面试题库

面试题:Ruby中委托模式与Forwardable模块基础应用

请简述Ruby中委托模式的概念,以及Forwardable模块如何实现委托模式。请编写一段Ruby代码示例,展示使用Forwardable模块将一个类的方法委托给另一个类。
40.8万 热度难度
编程语言Ruby

知识考点

AI 面试

面试题答案

一键面试

委托模式概念

委托模式是一种设计模式,它允许一个对象(委托者)将部分职责委托给另一个对象(受托者)。通过这种方式,委托者可以借助受托者的功能来完成某些任务,而不需要自己实现这些功能,从而实现代码的复用和解耦。

Forwardable模块实现委托模式

在Ruby中,Forwardable模块提供了一种简单的方式来实现委托模式。它允许一个类将某些方法调用转发到另一个对象。通过使用def_delegatordef_delegators方法,我们可以很方便地定义委托关系。

代码示例

require 'forwardable'

class HelperClass
  def perform_action
    "Action performed by HelperClass"
  end
end

class MainClass
  extend Forwardable
  def_delegator :@helper, :perform_action

  def initialize
    @helper = HelperClass.new
  end
end

main_obj = MainClass.new
puts main_obj.perform_action

在上述代码中:

  1. HelperClass是受托者,包含需要被委托的方法perform_action
  2. MainClass是委托者,通过extend Forwardable引入Forwardable模块的功能。
  3. 使用def_delegator :@helper, :perform_actionperform_action方法委托给@helper对象,这里@helperHelperClass的实例。
  4. 最后创建MainClass的实例并调用perform_action方法,实际调用的是HelperClass实例的perform_action方法。