组合对象
Coddy Ruby for C++ Developers 课程的第 31 课,共 48 课。
C++ 组合可以存储值、引用或智能指针,每种方式都有不同的所有权和生命周期规则。Ruby 实例变量会保留对协作者的引用,但不会自动克隆它们。委托可以让行为在不使用继承的情况下发生变化。确保协作者满足所需的调用契约,不要以为仅仅存储它就能使其兼容。
C++:完整程序
#include <iostream>
struct Policy {int factor;int apply(int n)const{return factor*n;}};
struct Service {const Policy& policy;int run(int n)const{return policy.apply(n);}};
int main() {
Policy p{2};Service s{p};std::cout<<s.run(3)<<"\n";
}
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)
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
Ruby for C++ Developers中的所有课
自己练习: Ruby 在线编译器