sdg*_*sdh 5 java oop design-patterns interface
假设我在用Java建模不同的动物.每只动物都有这些能力的组合:散步,游泳和飞翔.例如,能力集是不变的.
我可以将此信息存储为返回常量的getter.例如:
public class Penguin implements Animal {
public boolean canWalk() {
return true;
}
public boolean canSwim() {
return true;
}
public boolean canFly() {
return false;
}
// implementation...
}
Run Code Online (Sandbox Code Playgroud)
然后运行时检查:
if (animal.canFly()) {
// Fly!
}
Run Code Online (Sandbox Code Playgroud)
或者我可以使用"标记"界面:
public class Penguin implements Animal, Flyer, Swimmer {
// implementation...
}
Run Code Online (Sandbox Code Playgroud)
然后运行时检查:
if (animal instanceof Flyer) {
// Fly!
}
Run Code Online (Sandbox Code Playgroud)
每种方法的优点和缺点是什么?
标记接口在现代Java中是一种反模式,在早期需要,因为无法直接向类添加元数据."现代"方法是注释:
@Retention(RetentionPolicy.RUNTIME)
@interface Flyer {
}
@Retention(RetentionPolicy.RUNTIME)
@interface Swimmer {
}
@Flyer @Swimmer
public class Penguin implements Animal {
}
Run Code Online (Sandbox Code Playgroud)
并运行时检查:
if(Animal.class.isAnnotationPresent(Flyer.class)) {
// fly!
}
Run Code Online (Sandbox Code Playgroud)
如果您只想知道是否Animal具有此特征,那么您可以使用此方法,即航班和游泳能力是纯元数据.
你想要实现什么目标?我不会称之为OOP,因为OOP方法通常不会查询功能并执行特定于对象的条件逻辑,而是使用多态.