下图摘自我的演讲幻灯片。我已经使用组合和继承来编写一个Student - Person
类,我认为它们都很合理。
(我知道如果一个人可以有很多职位 - 1:n ,那么继承不起作用,所以我只接受大约 1 人:2 个职位关系)。
使用继承的代码:
class Person
attr_accessor :name, :gender, :height, :weight
def initialize(name, gender, height, weight)
@name = name
@gender = gender
@height = height
@weight = weight
end
def cry
"woooo"
end
end
class Student < Person
attr_accessor :student_id
def initialize(name, gender, height, weight, student_id)
super(name, gender, height, weight)
@student_id = student_id
end
def study
"Student #{name} with #{student_id} is studying now"
end
end
s = Student.new("Lin", "Male", 173, 75, 666777)
puts s.cry()
puts s.study
使用组合的代码:
class Person
attr_accessor :name, :gender, :height, :weight, :position
def initialize(name, gender, height, weight, position = nil)
@name = name
@gender = gender
@height = height
@weight = weight
@position = position
end
def cry
"woooo"
end
end
class Student
attr_accessor :student_id
def initialize(student_id)
@student_id = student_id
end
def study
"#{student_id} is studying now"
end
end
s = Student.new(666777)
p = Person.new("Lin", "Male", 173, 75, s)
puts p.cry()
puts p.position.study
而且我发现使用组合的代码有一个不好的方面,我不能student
叫他的名字。我的意思是我不能让 study() 方法返回像继承代码那样的东西:
"Student #{name} with #{student_id} is studying now"