Java中多重继承的替代方案 [英] Alternative of Multiple inheritance in Java

查看:559
本文介绍了Java中多重继承的替代方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了两个bean

I have created two beans

class BackPageBean{
   String backPage = null;
  :
  :
  :
}


class InformationMessageBean{
   String informationMessage = null;
  :
  :
  :
}

现在,如果一个类是反向识别的,那么它将扩展backPageBean,或者如果它需要显示某种消息,那么它扩展了InformationMessageBean。

Now, if a class is backpage aware then it will extend backPageBean, or if it need to show some kind of message then it extends 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,因为我们没有多重继承,那么该方法应该是什么?


Now the problem is, if i want to have a bean which is both BackPageAware as well as InformationAware then, as we don't have multiple inheritance, what should be the approach?

推荐答案

只是为了澄清我的评论。

Just to clarify my comment.


就像Darth Eru说的那样创建
两个接口和两个默认的
实现。如果你有一个需要这两种行为的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中多重继承的替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆