추상 기반 동작
Coddy의 Swift 개발자를 위한 Dart 코스 레슨. 48개 중 35번째.
Swift는 추상 클래스를 직접 선언하지 않습니다. 확장 기능이 있는 프로토콜로 관련 계약과 기본 동작을 표현할 수 있습니다. Dart의 추상 클래스는 언어 수준에서 추상 요구사항과 부분 구현을 제공합니다.
추상 클래스는 직접 인스턴스화할 수 없습니다. 추상 요구사항과 구체적인 공통 동작을 함께 정의할 수 있습니다. 구체 메서드는 하위 클래스에서 제공하는 특수화된 재정의 메서드를 호출할 수 있습니다.
완전한 Swift 프로그램:
import Foundation
protocol Shape{func name()->String};extension Shape{func label()->String{"shape:"+name()}};struct Circle:Shape{func name()->String{"circle"}}
print(Circle().label())
완전한 Dart 프로그램:
abstract class Shape{String name();String label()=>'shape:'+name();}
class Circle extends Shape{String name()=>'circle';}
void main(){print(Circle().label());}챌린지
쉬움추상 클래스 Charge에 추상 메서드 cost(int units)와 두 비용을 동적 디스패치로 합산하는 구체 메서드 pair(int a,int b)를 구현하세요. FlatCharge(int fee)는 Charge를 확장합니다. 비용은 단위 수가 0이면 0이고, 그렇지 않으면 수수료입니다. UnitCharge(int rate)는 Charge를 확장합니다. 비용은 요율에 단위 수를 곱한 값입니다. 입력은 모드 flat 또는 unit, 금액, 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));
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Swift 개발자를 위한 Dart의 모든 레슨
직접 연습해 보세요: 온라인 Dart 컴파일러