我正在研究Sandi Metz的实用面向对象设计。在第4章,创建灵活的接口中,我将看到一些UML图,以显示两个类的交互和消息。例如,下面是该书中的以下图表:
此图像的描述如下:
因此,此序列图可以如下读取:客户Moe将triple_trips消息发送到Trip类,该类被激活以对其进行处理,然后在完成后返回响应。
下面的实现是否准确?
class Customer
attr_reader :name, :on_date, :of_difficulty, :need_bike
def initialize(name, on_date, of_difficulty, need_bike)
@name = name
@on_date = on_date
@of_difficulty = of_difficulty
@need_bike = need_bike
end
end
class Trip
attr_reader :trip
def initialize(trip)
@trip = trip
end
def suitable_trips(on_date, of_difficulty, need_bike)
#gives list of suitable trips based on factors
end
end
moe = Customer.new("moe", "now", "easy", "yes")
trip = Trip.new('Grand Canyon')
trip.suitable_trips(moe.on_date, moe.of_difficulty, moe.need_bike)
有时候我想我明白了,但是随后我会遇到另一个UML图,然后在措词上感到困惑,尤其是在涉及接收方和发送方时。我只想确保我做对了,所以我完全了解方法应该去哪里以及在哪个类中。
答案 0 :(得分:0)
因此,此序列图可以如下读取:
Customer
Moe将suitable_trips
消息发送到Trip
类,该类将被激活以对其进行处理,然后在完成后返回回应。
完全按照规定实施。
class Trip
class << self # class methods
def suitable_trips(on_date, of_difficulty, need_bike)
# gives list of suitable trips based on factors
[Trip.new(...), Trip.new(...), ...]
end
end
end
class Customer
attr_reader :name
def initialize(name)
@name = name
end
# this is a search function, specific for Moe
def best_fit(on_date, of_difficulty, need_bike)
trips = Trip.suitable_trips(on_date, of_difficulty, need_bike)
# get the best accordingly to some rules
# that are specific for Moe
trips.find { |trip| ... }
end
end
并像这样使用它:
moe = Customer.new("Moe")
moe.best_fit("2019-06-01", :hard, false)
#⇒ Trip instance or `nil`
旁注:关于Ruby的书籍很多,我的个人建议是选择其中一本。桑迪·梅斯(Sandi Metz)可能是一位伟大的民粹主义者,但是从真正擅长 coding 的人那里读教程是有意义的。