Search code examples
javamixinstraits

java traits or mixins pattern?


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


Solution

  • 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?)

    In pseudo-code:

    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(); }
    }
    

    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.