java traits还是mixins模式? [英] java traits or mixins pattern?

查看:477
本文介绍了java traits还是mixins模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在java中模拟mixins或traits?基本上,我需要一种方法来进行多重继承,这样我就可以将常用的业务逻辑添加到几个类中

Is there a way to emulate mixins or traits in java? basically, I need a way to do multiple inheritance so I can add common business logic to several classes

推荐答案

我会封装所有的将业务逻辑转换为新类 BusinessLogic ,并让每个需要 BusinessLogic 的类调用该类。如果您需要为您的类调用 BusinessLogic 的单个根目录层次结构,则还必须创建一个接口( BusinessLogicInterface ?)

I would encapsulate all of the business logic into a new class BusinessLogic and have each class that needs BusinessLogic make calls to the class. If you need a single rooted heirarchy for your classes that make calls to BusinessLogic, you'll have to create an interface as well (BusinessLogicInterface?)

在伪代码中:

interface BusinessLogicInterace
{
    void method1();
    void method2();
}

class BusinessLogic implements BusinessLogicInterface
{
    void method1() { ... }
    void method2() { ... }
}

class User 
    extends OtherClass 
    implements BusinessLogicInterface
{
    BusinessLogic logic = new BusinessLogic();

    @Override
    void method1() { logic.method1(); }

    @Override
    void method2() { logic.method2(); }
}

这不是最缺乏多重继承的最佳实现当界面有很多方法时,它变得非常麻烦。最有可能的是,您需要尝试重新设计代码以避免需要mixins。

This isn't the prettiest implementation to work around a lack of multiple inheritance and it becomes quite cumbersome when the interface has a lot of methods. Most likely, you'll want to try and redesign your code to avoid needing mixins.

这篇关于java traits还是mixins模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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