Menu
CoddyTech

컴포지션과 위임

Coddy의 C++ 개발자를 위한 Java 코스 레슨. 48개 중 38번째.

C++에서 값에 의한 합성은 소유된 하위 객체를 저장하는 반면, Java의 합성은 보통 다른 객체에 대한 참조를 저장합니다. 주입된 협력 객체를 보유하면 의도적으로 공유할 수 있습니다. 깊은 복사가 이루어진다고 가정하는 대신 누가 이를 변경할 수 있는지 문서화하세요.

C++

#include <iostream>
#include <optional>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <numeric>
#include <functional>
#include <stdexcept>
struct Fee { int value; int amount() const { return value; } };
struct Checkout { Fee fee; int total(int n) const { return n+fee.amount(); } };
int main() {
  std::cout << std::boolalpha;
  Fee fee{4}; Checkout checkout{fee}; fee.value=7; std::cout << checkout.total(6) << "\n";
}

Java

import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class Example {
interface Rate {int cost(int n);}static class Bill {private final Rate rate;Bill(Rate rate){this.rate=rate;}int total(int n){return rate.cost(n);}}
public static void main(String[] args) {
Bill b=new Bill(n->n+17);System.out.println(b.total(5));
}
}

예제는 각 언어의 동작을 분리해 보여 주며 서로 다른 값을 사용할 수 있습니다. 각 예제를 별도로 추적하세요. 두 예제의 예상 출력이 일치한다고 가정하지 않습니다. Java 과제에서는 수정 가능한 클래스를 통해 새로운 입력에 같은 개념을 적용합니다.

challenge icon

챌린지

쉬움

입력은 단가와 사용량 순서이며, 둘 다 음이 아닌 값입니다. cost(int)를 구현하는 Rate(int)와 제공된 협력 객체에 위임하여 total(int)을 구현하는 UsageBill(Rate)를 작성하세요. 총액을 반환하세요.

Exercise.solve(List<String> input)에서 마지막 줄바꿈 없이 정확한 결과 텍스트를 반환하세요. 잠금 상태로 표시된 Main.java는 모든 입력 줄을 읽고 반환된 텍스트를 마지막에 줄바꿈 하나를 붙여 출력합니다. 편집 가능한 메서드 안에서 출력하지 마세요. 별도로 명시되지 않는 한 모든 정수와 산술 결과는 Java int 범위에 들어갑니다.

편집 가능한 파일: Rate.java, UsageBill.java, Exercise.java, Text.java. Text.java는 재사용 가능한 파싱 및 서식 지정 도우미를 제공합니다. 모든 파일은 이름 없는 패키지에 있으며 함께 컴파일됩니다. Main.java가 유일한 진입점이며 편집할 수 없습니다.

잠금 상태로 표시된 드라이버는 입력 사례를 실행하기 전에 새로 생성한 별도의 객체에서 필수 클래스 API도 호출합니다. 해당 API를 구현하세요. 최종 출력만 하드코딩하는 것으로는 충분하지 않습니다.

직접 해보기

import java.io.*;
import java.util.*;
public class Main {
    private static void check(boolean condition) {
        if (!condition) throw new AssertionError("Required public API behavior failed");
    }
    public static void main(String[] args) throws Exception {
        List<String> input = new ArrayList<>();
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String line;
        while ((line = reader.readLine()) != null) input.add(line);
        check(new Rate(6).cost(3)==18);Rate special=new Rate(1){public int cost(int n){return n+17;}};check(new UsageBill(special).total(5)==22);
        System.out.println(Exercise.solve(input));
    }
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

C++ 개발자를 위한 Java의 모든 레슨

직접 연습해 보세요: 온라인 Java 컴파일러