组合对象
Coddy 面向 Java 开发者的 Ruby 课程的第 31 课,共 48 课。
Java 和 Ruby 都通过保留对协作对象的引用来组合对象。存储子对象不会自动克隆它,也不会转移其独占所有权。委托可以在不使用继承的情况下提供灵活的行为。构造函数可以在 Java 中接收抽象类型,也可以在 Ruby 中接收兼容的鸭子类型对象。
Java:完整程序
import java.util.*;
public class Main {
static class Lens { String label() { return "wide"; } }
static class Camera {
private final Lens lens;
Camera(Lens lens) { this.lens = lens; }
String label() { return lens.label(); }
}
public static void main(String[] args) {
System.out.println(new Camera(new Lens()).label());
}
}Ruby:完整程序
class Lens
def label; "wide"; end
end
class Camera
def initialize(lens); @lens = lens; end
def label; @lens.label; end
end
puts Camera.new(Lens.new).label挑战
简单定义 Leg(minutes),并提供 minutes 读取器;定义 Route,并提供 add(leg) 和 total。Route 初始为空,用于存储传入的路段,并计算分钟数总和。solve 读取各路段的时长并返回总时长。
从 solve(input) 返回文本,不要打印。锁定的驱动程序会打印返回的文本,并在末尾添加一个换行符,同时独立检查必需的公共 API。
你的代码写在 exercise.rb、leg.rb 和 route.rb 中。main.rb 包含提供的输入/输出代码,不能编辑。
亲手试试
require_relative 'exercise'
require_relative 'leg'
require_relative 'route'
def check(value)
raise 'Public API check failed' unless value
end
a = Route.new; b = Route.new
a.add(Leg.new(7)); a.add(Leg.new(2))
check(a.total == 9 && b.total == 0 && Leg.new(4).minutes == 4)
puts solve(STDIN.read)
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Java 开发者的 Ruby中的所有课
自己练习: Ruby 在线编译器