추상 기반 동작
Coddy의 R 개발자를 위한 Dart 코스 레슨. 48개 중 35번째.
R S3는 객체가 생성될 때 추상 메서드를 강제하지 않습니다. 기본 제네릭 메서드는 특화된 동작이 누락되었을 때 에러를 발생시킬 수 있습니다. 다른 R 객체 시스템은 다른 규칙을 가집니다. Dart 추상 클래스는 요구 사항을 직접 선언하며 특화된 메서드를 호출하는 구체적인 동작을 제공할 수도 있습니다.
추상 클래스는 직접 인스턴스화할 수 없습니다. 추상 요구 사항과 구체적인 공유 동작을 결합할 수 있습니다. 구체 메서드는 서브클래스가 제공하는 특화된 오버라이드를 호출할 수 있습니다.
전체 R 프로그램:
shape_name <- function(x) UseMethod("shape_name")
shape_name.default <- function(x) stop("implement shape_name")
shape_name.circle <- function(x) "circle"
label <- function(x) paste0("shape:", shape_name(x))
circle <- structure(list(), class = "circle")
cat(label(circle), "\n", sep = "")
전체 Dart 프로그램:
abstract class Shape{String name();String label()=>'shape:'+name();}
class Circle extends Shape{String name()=>'circle';}
void main(){print(Circle().label());}챌린지
쉬움동적 디스패치를 사용하여 두 비용의 합을 구하는 구체 메서드 pair(int a,int b)와 추상 메서드 cost(int units)를 갖는 추상 클래스 Charge를 구현하세요. FlatCharge(int fee)는 Charge를 상속합니다. units가 0이면 cost는 0이고, 그렇지 않으면 fee입니다. UnitCharge(int rate)는 Charge를 상속합니다. cost는 rate에 units를 곱한 값입니다. 입력은 모드 flat 또는 unit, amount, a, b이며, 모두 0 이상 100 이하의 정수입니다. pair 결과를 출력하세요.
수정 가능한 파일에서 아무것도 출력하지 마세요. 제공된 exercise.dart는 입력을 파싱하고 결과를 반환하며, 잠긴 드라이버가 공개 API를 독립적으로 검증하고 줄바꿈 하나와 함께 결과를 출력합니다.
작성한 코드는 Charge.dart, FlatCharge.dart, UnitCharge.dart, exercise.dart에 들어갑니다. main.dart는 제공된 입출력 코드를 담고 있으며 편집할 수 없습니다.
직접 해보기
import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'Charge.dart';
import 'FlatCharge.dart';
import 'UnitCharge.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
final Charge a=FlatCharge(7),b=UnitCharge(3);check(a.cost(0)==0 && a.cost(2)==7 && a.pair(1,2)==14);check(b.cost(4)==12 && b.pair(2,3)==15);
stdout.writeln(solve(input));
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
R 개발자를 위한 Dart의 모든 레슨
직접 연습해 보세요: 온라인 Dart 컴파일러