합성과 위임
Coddy의 C 개발자를 위한 Java 코스 레슨. 48개 중 38번째.
C 구조체 멤버는 하위 객체를 값으로 저장하지만, 포인터 멤버는 의도적으로 협력 객체를 공유할 수 있습니다. Java의 합성은 일반적으로 객체 참조를 유지합니다. 협력 객체를 전달받는 생성자는 기본 객체로 대체하지 말고 전달받은 객체에 위임해야 합니다. 깊은 복사를 가정하는 대신 누가 공유 상태를 변경할 수 있는지 명시하세요.
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <stdarg.h>
#include <errno.h>
#include <limits.h>
#include <ctype.h>
struct Fee {int value;};
struct Checkout {struct Fee fee;};
static int total(const struct Checkout *checkout,int amount) { return amount+checkout->fee.value; }
int main(void) {
struct Fee fee={4}; struct Checkout checkout={fee}; fee.value=7; printf("%d\n",total(&checkout,6));
return 0;
}
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 과제는 편집 가능한 클래스를 통해 새로운 입력에 같은 개념을 적용합니다.
챌린지
쉬움입력은 단가와 사용량 순서이며, 둘 다 음이 아닌 정수입니다. 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));
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C 개발자를 위한 Java의 모든 레슨
직접 연습해 보세요: 온라인 Java 컴파일러