面向?qū)ο缶幊蹋∣bject-Oriented Programming,OOP)是一種編程范式,它使用“對象”來表示現(xiàn)實世界中的事物,通過封裝、繼承和多態(tài)等特性來實現(xiàn)代碼的復(fù)用和模塊化。在Ruby中,面向?qū)ο缶幊痰膽?yīng)用非常廣泛,以下是一些常見的應(yīng)用場景:
封裝是將對象的屬性和方法隱藏起來,只暴露必要的接口。這樣可以保護(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
繼承允許一個類(子類)繼承另一個類(父類)的屬性和方法。子類可以重寫或擴(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
多態(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
模塊是一種代碼復(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
抽象類是不能實例化的類,通常用于定義一些通用的方法和屬性,供子類實現(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ò)展的代碼。