考虑以下定义和实现 Foo
接口(interface)的类:
public class MyClass {
public Foo getFoo() {
return new FooImpl();
}
public void fooMethod(Foo foo) {
final fooImpl = (FooImpl) foo;
fooImpl.hiddenMethod();
}
public interface Foo {
void doSomething();
}
private class FooImpl implements Foo {
public void doSomething();
void hiddenMethod() {
}
}
}
外部类将调用 MyClass.getFoo()
来获取一个 Foo
对象,并可能将其传回给 fooMethod()
。 fooMethod()
期望 Foo
的 FooImpl
实现并将 Foo
转换为 FooImpl
所以它可以调用包私有(private)方法 hiddenMethod()
。
我的问题是,我并不热衷于将 Foo
转换为 FooImpl
。我可以使用另一种模式来做同样的事情吗?
提前致谢...
最佳答案
这里的问题是您隐含地违反了封装原则。您的类中有一个方法取决于实现,因此不是 Foo 接口(interface)的一部分。这违反了面向对象的原则,这只是冰山一角。如果你想设计一个新的 Foo 实现类,但没有你想调用的方法怎么办?
你应该重新设计你的代码,这样你就可以实现这个只调用 Foo 接口(interface)的方法。
关于java - 有什么办法可以避免转换这种类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22995800/