java traits还是mixins模式? [英] java traits or mixins pattern?
问题描述
有没有办法在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屋!