Java 21密封类:构建类型安全的领域模型

Java 21的密封类(Sealed Classes)功能彻底改变了我们设计类层次结构的方式。通过精确控制哪些类可以继承或实现特定的类或接口,密封类为构建类型安全的领域模型提供了强大的工具

核心概念

1. 密封类的基本语法

密封类使用sealed关键字声明,并通过permits子句指定允许的子类:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public sealed class Shape permits Circle, Square, Rectangle {
    // 基类实现
}

public final class Circle extends Shape {
    private final float radius;
    // 具体实现
}

public non-sealed class Square extends Shape {
    private final double side;
    // 具体实现
}

2. 密封接口

接口同样可以声明为密封的,限制实现类:

1
2
3
4
5
6
7
8
9
public sealed interface Transport permits Car, Truck, Bike {
    void move();
}

public final class Car implements Transport {
    public void move() {
        System.out.println("Driving on road");
    }
}

设计模式应用

1. 领域建模

密封类特别适合领域驱动设计(DDD)中的值对象和领域事件:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public sealed interface DomainEvent 
    permits UserCreatedEvent, UserUpdatedEvent, UserDeletedEvent {
    
    Instant occurredAt();
    UUID aggregateId();
}

public record UserCreatedEvent(UUID userId, String username) 
    implements DomainEvent {
    // 实现方法
}

2. 状态机实现

使用密封类实现有限状态机:

1
2
3
4
5
6
7
8
9
public sealed interface OrderState permits Draft, Confirmed, Shipped, Delivered {
    boolean canTransitionTo(OrderState next);
}

public final class Draft implements OrderState {
    public boolean canTransitionTo(OrderState next) {
        return next instanceof Confirmed;
    }
}

最佳实践

1. 模式匹配结合

密封类与模式匹配完美结合:

1
2
3
4
5
6
7
public String processShape(Shape shape) {
    return switch (shape) {
        case Circle c -> "Circle with radius: " + c.radius();
        case Square s -> "Square with side: " + s.side();
        case Rectangle r -> "Rectangle area: " + (r.length() * r.width());
    };
}

2. 反射支持

Java反射API提供了对密封类的支持:

1
2
3
4
5
Class<?> shapeClass = Shape.class;
if (shapeClass.isSealed()) {
    Class<?>[] permittedSubclasses = shapeClass.getPermittedSubclasses();
    // 处理允许的子类
}

性能考虑

密封类在编译时进行优化,运行时性能与传统类层次结构相当。JVM能够优化类型检查流程,避免不必要的性能开销。

密封类概念

本博客已稳定运行
共14篇文章 · 共8.03k字
使用 Hugo 构建
主题 StackJimmy 设计 由 iTang 优化