背景
我有一个界面
public interface ThingRegistry {
public Set<Thing> getAllThings();
public Set<Thing> getAllThingsWithProperty(String property);
}
实施方案
public class MemoryThingRegistry {
private final Set<Thing> things = new HashSet<>();
public Set<Thing> getAllThings() {
return Collections.unmodifiableSet(this.things);
}
public Set<Thing> getAllThingsWithProperty(final String property) {
return this.things.stream().filter((thing) -> thing.hasProperty(property)).collect(Collectors.toUnmodifiableSet());
}
}
问题
我的注册表中的getAllThings()
返回的Set会反映出对注册表所做的任何更改
然而,getAllThingsWithProperty()
返回的Set不会反映这些更改
问题
是否有任何使用标准Java库或一些非常常见的第三方库的方法,可以使getAllThingsWithProperty()
的返回值成为一个"活动"的子Set
?也就是说,它是由原始Set
支持的,但每次访问时都会重新应用Predicate
?最好是适用于任何Collection
,因为我还有另一个使用List
的注册表接口。
我知道我可以编写自己的Set
实现,但我更希望避免这样做。
Set
实现听起来似乎是一件大事,但实际上你可以简单地在一个类中包装标准的HashSet,并且还利用观察者模式。这样,当主集合发生变化时,你就可以“自动”更新你的子集。但显然,如果需要的话,你还必须使用一些同步手段来确保线程安全。 - undefined