子类化 Guava 的 ImmutableSet 的适当方法

发布于 2025-01-01 12:21:26 字数 733 浏览 2 评论 0原文

我有一门类似这样的课程,

class Receipt
{
     private Set<Order> orders;
     public Receipt(Set<Order> orders)
     {
         this.orders = ImmutableSet.copyOf(orders)
     }   
}

这对我很有帮助。

然而,由于某些类型擦除&由于我面临的持久性问题,我现在想介绍一种

class OrderSet extends Set<Order> {}

显然我无法扩展 Set 的形式,因为它是一个接口。我想保持我的实现不可变。但是,我无法扩展 ImmutableSet,如文档所述:

注意:虽然这个类不是final的,但它不能被子类化 在其包之外,因为它没有公共或受保护的构造函数。 因此,这种类型的实例保证是不可变的。

我可以使用组合,为 OrderSet 提供 ImmutableSet 的后备集合,并将所有 Set 方法委托给它。然而,这似乎有点矫枉过正。

还有另一种方法可以在这里实现非泛型子类吗?

I have a class along the lines of

class Receipt
{
     private Set<Order> orders;
     public Receipt(Set<Order> orders)
     {
         this.orders = ImmutableSet.copyOf(orders)
     }   
}

This has served me well.

However, because of some type-erasure & persistence issues I'm facing, I'd like to now introduce a form of

class OrderSet extends Set<Order> {}

Obviously I can't extend Set<Order>, as it's an interface. I'd like to keep my implementation as immutable. However, I can't extend ImmutableSet<Order>, as the docs state:

Note: Although this class is not final, it cannot be subclassed
outside its package as it has no public or protected constructors.
Thus, instances of this type are guaranteed to be immutable.

I could use composition, giving OrderSet a backing collection of ImmutableSet and delegate all the Set methods to it. However, this seems overkill.

Is there another way I can achieve a non-generic subclass here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尸血腥色 2025-01-08 12:21:26

不,构图并不是矫枉过正,这正是要走的路。

您应该按如下方式创建您的 OrderSet ,因为正如 Louis 在评论中强调的那样,这个用例正是它们的用途:

public class OrderSet extends ForwardingSet<Order> {
  private final ImmutableSet<Order> orders;
  public class OrderSet (Set<Order> orders) {
    this.orders = ImmutableSet.copyOf(orders);
  }
  protected ImmutableSet<Order> delegate() { return orders; }
}

Guava 中的不可变类被设计成这样你不延长它们。您必须使用组合,这正是正确的方法。

No, composition isn't overkill, it's exactly the way to go.

You should create your OrderSet as follows because, as Louis emphasizes in the comments, this use case is exactly what they're meant for:

public class OrderSet extends ForwardingSet<Order> {
  private final ImmutableSet<Order> orders;
  public class OrderSet (Set<Order> orders) {
    this.orders = ImmutableSet.copyOf(orders);
  }
  protected ImmutableSet<Order> delegate() { return orders; }
}

The immutable classes in Guava are designed so that you don't extend them. You have to use composition and it's precisely the right way to go.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文