1

下の図は私の講義スライドから取ったものです。私は合成と継承の両方を使用してStudent - Personクラスをコーディングしましたが、どちらもかなり合理的だと思います。

(1人が多くのポジションを持つことができるかどうかは知っています- 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そして、コンポジションを使用したコードには 1 つの悪い面があることがわかりました。彼の名前を呼び出すことができません。つまり、 study() メソッドが継承コードのように何かを返すようにすることはできません。

"Student #{name} with #{student_id} is studying now"
4

0 に答える 0