gpt4 book ai didi

java - 私有(private)内部类实现接口(interface)而不是父类,为什么?

转载 作者:行者123 更新时间:2023-12-01 08:10:10 36 4
gpt4 key购买 nike

我找到了一个代码,其中有一个内部私有(private)类,它实现一个接口(interface)并从它的封闭类返回值。制作这样的东西而不是直接在封闭类中实现接口(interface)有什么好处吗?

像这样:

public class Foo {
public Whatever getWhatever() { return new Boo(); }
private Whatever boo;
private int n;
private class Boo implements Whatever {
@Override int getN() { returns n; }
}
}

也许这里有某种设计模式,或者可能有一些与此类似的设计模式?

最佳答案

一个重要原因是 Foo 的单个实例可以创建并返回许多单独的 Boo 实例。如果你想象 Foo 是一个集合类,而 Boo 是一个迭代器;这将允许对同一集合进行多个并发迭代,同时保持集合的实现细节私有(private)。

关于java - 私有(private)内部类实现接口(interface)而不是父类,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18060352/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com