我创建了两个bean
class BackPageBean{
String backPage = null;
:
:
:
}
class InformationMessageBean{
String informationMessage = null;
:
:
:
}
现在,如果一个类是支持后台的,那么它会扩展 backPageBean,或者如果它需要显示某种消息,那么它会扩展 InformationMessageBean。
class BackPageAware extends backPageBean{
}
class InfoMessAware extends InformationMessageBean{
}
someFunction () {
if ( theObject instanceOf backPageBean ) {
prepareTheBackPage ( theObject.getBackPage() );
}
if ( theObject instanceOf InformationMessageBean ) {
showtheInformation ( theObject.getMessage() );
}
}
现在的问题是,如果我想要一个既是 BackPageAware 又是 InformationAware 的 bean,因为我们没有多重继承,应该采用什么方法?
最佳答案
只是为了澄清我的评论。
Just like Darth Eru says you create the two interfaces and the two default implementations. When you have a bean that needs both of the behaviours you have that class implement the two interfaces but you also create variables of the default implementations. This way you still dont need to duplicate any code.
interface InfoMessAware {
String getMessage();
}
interface BackPageAware {
String getBackPage();
}
class DefaultInfoMessAware {
String getMessage() {
return "message";
}
}
class DefaultBackPageAware {
String getBackPage() {
return "backPage";
}
}
class MyBean implements InfoMessAware, BackPageAware {
private InfoMessAware messAware = new DefaultInfoMessAware();
private BackPageAware backPageAware = new DefaultBackPageAware();
String getMessage() {
return messAware.getMessage();
}
String getBackPage() {
return backPageAware.getBackPage();
}
}
关于java - Java中多重继承的替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1038314/