溫馨提示×

Ruby面向?qū)ο缶幊倘绾螒?yīng)用

小樊
81
2024-11-06 05:18:47
欄目: 編程語言

面向?qū)ο缶幊蹋∣bject-Oriented Programming,OOP)是一種編程范式,它使用“對象”來表示現(xiàn)實世界中的事物,通過封裝、繼承和多態(tài)等特性來實現(xiàn)代碼的復(fù)用和模塊化。在Ruby中,面向?qū)ο缶幊痰膽?yīng)用非常廣泛,以下是一些常見的應(yīng)用場景:

1. 封裝(Encapsulation)

封裝是將對象的屬性和方法隱藏起來,只暴露必要的接口。這樣可以保護(hù)對象內(nèi)部的狀態(tài)不被外部直接修改,提高代碼的安全性和可維護(hù)性。

class Car
  attr_reader :make, :model, :year

  def initialize(make, model, year)
    @make = make
    @model = model
    @year = year
  end

  def drive
    puts "Driving the #{@make} #{@model}..."
  end
end

car = Car.new("Toyota", "Corolla", 2020)
car.drive

2. 繼承(Inheritance)

繼承允許一個類(子類)繼承另一個類(父類)的屬性和方法。子類可以重寫或擴(kuò)展父類的方法,實現(xiàn)代碼的復(fù)用。

class Vehicle
  attr_accessor :make, :model, :year

  def initialize(make, model, year)
    @make = make
    @model = model
    @year = year
  end

  def drive
    puts "Driving..."
  end
end

class Car < Vehicle
  def drive
    puts "Driving the #{@make} #{@model}..."
  end
end

bike = Vehicle.new("Honda", "CBR", 2021)
bike.drive

car = Car.new("Toyota", "Corolla", 2020)
car.drive

3. 多態(tài)(Polymorphism)

多態(tài)是指不同類的對象可以使用相同的接口。通過多態(tài),可以在運(yùn)行時根據(jù)對象的實際類型調(diào)用相應(yīng)的方法,提高代碼的靈活性和可擴(kuò)展性。

class Vehicle
  attr_accessor :make, :model, :year

  def initialize(make, model, year)
    @make = make
    @model = model
    @year = year
  end

  def drive
    puts "Driving..."
  end
end

class Car < Vehicle
  def drive
    puts "Driving the #{@make} #{@model}..."
  end
end

class Motorcycle < Vehicle
  def drive
    puts "Riding the #{@make} #{@model}..."
  end
end

vehicles = [Car.new("Toyota", "Corolla", 2020), Motorcycle.new("Honda", "CBR", 2021)]

vehicles.each do |vehicle|
  vehicle.drive
end

4. 模塊(Modules)

模塊是一種代碼復(fù)用的方式,可以將一組相關(guān)的函數(shù)和方法封裝在一個模塊中,然后在其他類中通過include關(guān)鍵字引入。

module Drivable
  def drive
    puts "Driving..."
  end
end

class Vehicle
  include Drivable

  attr_accessor :make, :model, :year

  def initialize(make, model, year)
    @make = make
    @model = model
    @year = year
  end
end

car = Vehicle.new("Toyota", "Corolla", 2020)
car.drive

5. 抽象類(Abstract Classes)

抽象類是不能實例化的類,通常用于定義一些通用的方法和屬性,供子類實現(xiàn)。

class Vehicle
  attr_accessor :make, :model, :year

  def initialize(make, model, year)
    @make = make
    @model = model
    @year = year
  end

  def drive
    raise NotImplementedError, "This method must be overridden in subclass"
  end
end

class Car < Vehicle
  def drive
    puts "Driving the #{@make} #{@model}..."
  end
end

class Motorcycle < Vehicle
  def drive
    puts "Riding the #{@make} #{@model}..."
  end
end

vehicles = [Car.new("Toyota", "Corolla", 2020), Motorcycle.new("Honda", "CBR", 2021)]

vehicles.each do |vehicle|
  vehicle.drive
end

通過這些面向?qū)ο缶幊痰奶匦?,Ruby可以編寫出結(jié)構(gòu)清晰、易于維護(hù)和擴(kuò)展的代碼。

0