面试题答案
一键面试- 通过模块混入实现多态的原理:
- 在Ruby中,模块混入(
include
)允许一个类使用模块中定义的方法。通过在不同类中包含相同模块,并在类中重新定义模块中的方法,可以实现多态。即不同类对同一个模块方法有不同的实现逻辑。
- 在Ruby中,模块混入(
- 确保混入模块后的类之间不会相互干扰:
- Ruby的模块和类是独立的命名空间。当一个类混入模块时,模块中的方法会被添加到类的方法集中。不同类对模块方法的实现是独立的,因为每个类都有自己的方法定义。只要在不同类中分别正确实现模块方法,就不会相互干扰。
- 完整代码示例:
module Flyable
def fly
raise NotImplementedError, "Subclasses must implement #fly"
end
end
class Bird
include Flyable
def initialize(wing_flap_frequency)
@wing_flap_frequency = wing_flap_frequency
end
def fly
puts "Bird is flying with wing flap frequency of #{@wing_flap_frequency} times per second."
end
end
class Plane
include Flyable
def initialize(engine_power)
@engine_power = engine_power
end
def fly
puts "Plane is flying with engine power of #{@engine_power} horsepower."
end
end
# 使用示例
bird = Bird.new(10)
bird.fly
plane = Plane.new(1000)
plane.fly
在上述代码中:
- 首先定义了
Flyable
模块,其中fly
方法抛出一个NotImplementedError
,这是为了确保混入该模块的类必须实现fly
方法。 Bird
类和Plane
类都混入了Flyable
模块。Bird
类在fly
方法中使用翅膀挥动频率来描述飞行逻辑,Plane
类在fly
方法中使用发动机功率来描述飞行逻辑。- 最后创建
Bird
和Plane
的实例,并调用fly
方法,展示不同类对fly
方法的不同实现。由于类和模块的命名空间机制,Bird
和Plane
对fly
方法的实现相互独立,不会相互干扰。