面向對象編程(Object-Oriented Programming,OOP)是一種編程范式,它使用“對象”來表示現實世界中的事物,通過封裝、繼承和多態等特性來實現代碼的復用和模塊化。在Ruby中,面向對象編程的應用非常廣泛,以下是一些常見的應用場景:
封裝是將對象的屬性和方法隱藏起來,只暴露必要的接口。這樣可以保護對象內部的狀態不被外部直接修改,提高代碼的安全性和可維護性。
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
繼承允許一個類(子類)繼承另一個類(父類)的屬性和方法。子類可以重寫或擴展父類的方法,實現代碼的復用。
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
多態是指不同類的對象可以使用相同的接口。通過多態,可以在運行時根據對象的實際類型調用相應的方法,提高代碼的靈活性和可擴展性。
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
模塊是一種代碼復用的方式,可以將一組相關的函數和方法封裝在一個模塊中,然后在其他類中通過include
關鍵字引入。
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
抽象類是不能實例化的類,通常用于定義一些通用的方法和屬性,供子類實現。
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
通過這些面向對象編程的特性,Ruby可以編寫出結構清晰、易于維護和擴展的代碼。