面试题答案
一键面试委托模式概念
委托模式是一种设计模式,它允许一个对象(委托者)将部分职责委托给另一个对象(受托者)。通过这种方式,委托者可以借助受托者的功能来完成某些任务,而不需要自己实现这些功能,从而实现代码的复用和解耦。
Forwardable模块实现委托模式
在Ruby中,Forwardable模块提供了一种简单的方式来实现委托模式。它允许一个类将某些方法调用转发到另一个对象。通过使用def_delegator
和def_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
在上述代码中:
HelperClass
是受托者,包含需要被委托的方法perform_action
。MainClass
是委托者,通过extend Forwardable
引入Forwardable模块的功能。- 使用
def_delegator :@helper, :perform_action
将perform_action
方法委托给@helper
对象,这里@helper
是HelperClass
的实例。 - 最后创建
MainClass
的实例并调用perform_action
方法,实际调用的是HelperClass
实例的perform_action
方法。