Menu
CoddyTech

组合对象

Coddy 面向 C 开发者的 Ruby 课程的第 31 课,共 48 课。

在 C 中,组合可以嵌入一个值,也可以保留指向协作者的指针,两者在复制和生命周期方面的影响不同。Ruby 的实例变量保留对象引用;赋值不会克隆协作者,也不会转移其独占所有权。委托可以在不使用继承的情况下实现灵活的行为。注入一个兼容的对象,并通过预期的契约调用它的方法。

C:完整程序

#include <stdio.h>
struct Policy {
    int factor;
    int (*apply)(const struct Policy *self, int quantity);
};
struct Order { const struct Policy *policy; };
static int multiply(const struct Policy *self, int quantity)
{
    return self->factor * quantity;
}
static int order_total(const struct Order *self, int quantity)
{
    return self->policy->apply(self->policy, quantity);
}
int main(void)
{
    struct Policy policy = {2, multiply};
    struct Order order = {&policy};
    printf("%d\n", order_total(&order, 3));
    return 0;
}

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
challenge icon

挑战

简单

定义 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)
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 C 开发者的 Ruby中的所有课

自己练习: Ruby 在线编译器