示例工程 ch03-types-collections
ch03-types-collections/lib/shapes.dart
/// 继承、接口、抽象类与 `sealed` 类 + 模式匹配。
///
/// 对照 Go:Go 只有"隐式接口 + struct 嵌入",没有继承;Dart 有单继承 + 任意多接口。
/// 对照 C:没有真正的多态,只能靠函数指针表(vtable)手工模拟。
library;
import 'dart:math' as math;
/// 抽象类:不能实例化,只能被继承。相当于 C 的"接口结构体 + 函数指针表"。
abstract class Shape {
const Shape();
/// 抽象成员:子类必须实现。相当于 Go 接口里的方法声明。
double get area;
/// 具体方法:子类直接继承,不用重写。
String describe() => '$runtimeType(area: ${area.toStringAsFixed(2)})';
}
/// `sealed` 类(Dart 3):**封闭**的类层次,子类必须在同一个库中声明。
/// 这让编译器可以对 `switch` 做穷尽性检查——少写一个分支就是编译错误。
sealed class Shape2 {
const Shape2();
double get area;
}
class Circle extends Shape2 implements Describable {
const Circle(this.radius);
final double radius;
@override
double get area => math.pi * radius * radius;
/// 实现 Describable 接口:Circle 及其子类都能被当 `Describable` 使用。
@override
String describe() => 'Circle(r=$radius)';
@override
bool operator ==(Object other) => other is Circle && other.radius == radius;
@override
int get hashCode => radius.hashCode;
}
final class Rectangle extends Shape2 {
const Rectangle(this.width, this.height);
/// 正方形:命名构造函数转发到主构造函数。
const Rectangle.square(double side) : this(side, side);
final double width;
final double height;
@override
double get area => width * height;
@override
bool operator ==(Object other) =>
other is Rectangle && other.width == width && other.height == height;
@override
int get hashCode => Object.hash(width, height);
}
final class Triangle extends Shape2 {
const Triangle(this.base, this.height);
final double base;
final double height;
@override
double get area => base * height / 2;
@override
bool operator ==(Object other) =>
other is Triangle && other.base == base && other.height == height;
@override
int get hashCode => Object.hash(base, height);
}
/// 穷尽 switch 表达式:**不需要 default**,因为 `Shape2` 是 sealed。
/// 新增一个子类时,这里会立刻变成编译错误——这正是 C/Go 都缺的穷尽性检查。
///
/// `NamedCircle` 必须排在 `Circle` 前面:模式匹配自上而下,先匹配更具体的子类型。
String label(Shape2 shape) => switch (shape) {
NamedCircle(:final name, :final radius) => '命名圆 $name r=$radius',
Circle(:final radius) => '圆形 r=$radius',
Rectangle(:final width, :final height) => '矩形 ${width}x$height',
Triangle(:final base, :final height) => '三角形底 $base 高 $height',
};
/// 形状面积求和:多态分派由运行期虚表完成,等价于 C 的函数指针、Go 的接口方法集。
double totalArea(Iterable<Shape2> shapes) =>
shapes.fold(0, (double sum, Shape2 s) => sum + s.area);
/// 接口:Dart 里任何类都能被 `implements`(隐式接口)。
abstract interface class Describable {
String describe();
}
/// 一个类可以 `extends` 一个父类、`implements` 任意多个接口。
class NamedCircle extends Circle implements Comparable<NamedCircle> {
const NamedCircle(super.radius, this.name);
final String name;
@override
String describe() => '$name: ${super.describe()}';
@override
int compareTo(NamedCircle other) => name.compareTo(other.name);
}