📜  Ruby 中的多态性

📅  最后修改于: 2022-05-13 01:54:41.200000             🧑  作者: Mango

Ruby 中的多态性


在 Ruby 中,没有其他编程语言中的变量类型。每个变量都是一个可以单独修改的“对象”。可以轻松地在每个对象上添加方法和函数。所以在这里,面向对象的编程起着重要的作用。在其他所有编程语言中都有许多面向对象编程的支柱,例如继承、封装等。其中一个支柱是多态性。

多态性是由两个词组成的Poly表示ManyMorph表示Forms 。因此,多态是一种能够使用不同对象执行相同方法的方法。在多态中,我们可以通过传递不同的输入对象,使用相同的函数获得不同的结果。也可以编写 If-Else 命令,但这只会使代码更冗长。为了避免这种情况,程序员提出了多态的概念。

在多态中,类具有不同的功能,但它们具有共同的干扰。多态性的概念可以在几个子类别下进行研究。

  1. 使用继承的多态性
  2. 使用 Duck-Typing 的多态性

  • 使用继承的多态性

继承是子类继承父类的属性和方法的属性。使用继承可以轻松实现多态性。可以用下面的例子来解释:
例子 :
# Ruby program of Polymorphism using inheritance
class Vehicle
    def tyreType
        puts "Heavy Car"
    end
end
   
# Using inheritance 
class Car < Vehicle
    def tyreType
        puts "Small Car"
    end
end
   
# Using inheritance 
class Truck < Vehicle
    def tyreType
        puts "Big Car"
    end
end
  
# Creating object 
vehicle = Vehicle.new
vehicle.tyreType()
   
# Creating different object calling same function 
vehicle = Car.new
vehicle.tyreType()
   
# Creating different object calling same function 
vehicle = Truck.new
vehicle.tyreType()

输出:

Heavy Car
Small Car
Big Car

上面的代码是执行基本多态性的一种非常简单的方法。在这里,使用 Car 和 Truck 等不同的对象调用tyreType方法。 Car 和 Truck 类都是 Vehicle 的子类。它们都继承了vehicle类的方法(主要是tyretype方法)。

  • 使用 Duck-Typing 的多态性
    在 Ruby 中,我们关注对象的功能和特性,而不是它的类。因此,Duck Typing 只不过是研究对象可以做什么而不是它实际上是什么的想法。或者,可以对对象而不是对象的类执行哪些操作。
    这是一个小程序来表示前面提到的过程。
    例子 :
    # Ruby program of polymorphism using Duck typing
      
    # Creating three different classes
    class Hotel
       
      def enters
        puts "A customer enters"
      end
       
      def type(customer)
        customer.type
      end
       
      def room(customer)
        customer.room
      end
       
    end
       
    # Creating class with two methods 
    class Single
       
      def type
        puts "Room is on the fourth floor."
      end
       
      def room
        puts "Per night stay is 5 thousand"
      end
       
    end
       
       
    class Couple
       
     # Same methods as in class single
      def type
        puts "Room is on the second floor"
      end
       
      def room
        puts "Per night stay is 8 thousand"
      end
       
    end
       
    # Creating Object
    # Performing polymorphism 
    hotel= Hotel.new
    puts "This visitor is Single."
    customer = Single.new
    hotel.type(customer)
    hotel.room(customer)
       
       
    puts "The visitors are a couple."
    customer = Couple.new
    hotel.type(customer)
    hotel.room(customer)
    

    输出 :

    This visitor is Single.
    Room is on the fourth floor.
    Per night stay is 5 thousand
    The visitors are a couple.
    Room is on the second floor
    Per night stay is 8 thousand
    

    在上面的示例中,客户对象在处理客户的属性(例如其“类型”和“房间”)方面发挥作用。这是多态性的一个例子。