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

チャレンジ

簡単

minutesリーダーを持つLeg(minutes)を定義します。add(leg)とtotalを持つRouteを定義します。Routeは空の状態で始まり、渡されたlegを保存して、minutesを合計します。solveはlegの所要時間を読み取り、合計を返します。

出力せずに、solve(input)からテキストを返してください。ロックされたドライバーは、返されたテキストを最後に改行を1つ付けて出力し、必要な公開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オンラインコンパイラ