Ruby Mixins
在阅读有关mixin的文章之前,您应该非常了解与面向对象编程有关的事情,尤其是在继承方面。
我们都知道Ruby不直接支持多重继承,这意味着一个子类不能具有多个父类。这仅表示它只能继承单个父类的功能。当我们必须使一个子类继承多个基类的功能时,我们可以从Mixins那里获得帮助。Mixins也可以被视为实现间接多个继承的机制。我们使用include方法来实现mixin,并且一个类可能具有的mixin数量没有限制。让我们借助语法和演示程序代码来理解mixins。
语法:
class M1
Include M2
Include M3
end范例1:
=begin
Program to demonstrate Mixins
=end
module Printhello
def prnt1
puts "Hello"
end
def prnt2
puts "Hi"
end
end
module Printbye
def prnt3
puts "Bye"
end
def prnt4
puts "Take Care"
end
end
class Nhooo
include Printhello
include Printbye
def Add
puts "Follow Nhooo on Instagram"
end
end
obj1 = Nhooo.new
obj1.prnt1
obj1.prnt2
obj1.prnt3
obj1.prnt4
obj1.Add输出:
Hello Hi Bye Take Care Follow Nhooo on Instagram
说明:
在上面的代码中,您可以观察到我们在Ruby中间接实现了mixins以及多重继承。Nhooo类现在有两个模块,即Printhello和Printbye。子类现在可以访问所有两个基类的所有方法或功能。这是使类在Ruby中继承的方式。
范例2:
=begin
Program to demonstrate Mixins
=end
module Parent_1
def a1
puts 'This is Parent one.'
end
end
module Parent_2
def a2
puts 'This is Parent two.'
end
end
module Parent_3
def a3
puts 'This is Parent three.'
end
end
class Child
include Parent_1
include Parent_2
include Parent_3
def display
puts 'Three modules have been included.'
end
end
object = Child.new
object.display
object.a1
object.a2
object.a3输出:
Three modules have been included. This is Parent one. This is Parent two. This is Parent three.
说明:
在上面的代码中,您可以观察到我们在Ruby中间接实现了mixins以及多重继承。子类现在具有三个模块,即Parent_1,Parent_2和Parent_3。子类现在可以访问所有三个基类的所有方法或功能。