我在我工作的代码库中经常看到这种习惯用法,本质上是:
Interface -> Abstract class that defines getters/setters -> Implementations
例如:
interface Foo{
void doSomethingA();
void doSomethingB();
}
abstract class AbstractFoo implements Foo{
protected int x;
protected String y;
int getX(){ return x;}
void setX(int x){ this.x = x;}
String getY(){ return y;}
void setY(String y){ this.y = y;}
}
//One or more concrete classes extending AbstractFoo
这个有名字吗?我能看到的唯一好处是扩展 AbstractFoo 的类不需要重新实现它们的 getter 和 setter。
最佳答案
这不是一种设计模式。
接口(interface)是显而易见的:每个实现接口(interface)的类都必须实现其方法 - 毫无疑问。
如果愿意,抽象类可以为每个方法提供默认行为。所以是的,这是为了方便子类开发人员。请记住,编写抽象类的人可能会提供至少一个具体的子类,因此他们会受益。
getter 和 setter 不是重点。任何好的 IDE 都可以为您生成它们。该功能对于复杂的默认行为更有意义。
看看 Joshua Bloch 在设计 Collection API 时如何在 java.util
包中使用这个习惯用法并取得巨大成功。
关于java - 这个模式/习语是什么?有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9437012/