简体   繁体   中英

Abstract class to hold common member variables

Can we use abstract class to just hold common member variables which are autowired. This was the classes extending the abstract class need not declare the member fields again. Is this a good design pattern ? If not what is a better way to achieve this ? Note : The abstract class does not have any methods.

abstract class Abs {  

    @autowired
    protected ClassA varA;  
    @Autowired
    protected ClassB varB;  
    @Autowired
    protected ClassC varC;  
    ...  
}

class My1 extends Abs {  

    public void methodA() {  
        //make call  
        varA.aCall()  
        varB.bCall()  
        varC.cCall()  
    }

Since you said in a comment that "The only reason for the abstract class is to hold common shared member variables", there is no reason for you to use abstract class inheritance for this purpose. If there were no requirement for the vars to be autowired, I would say declare them as public static final in an interface, which needs not be implemented as you could just reference them statically. Since they do need to be autowired, and you cannot autowire static variables, I suggest putting them in a bean dedicated to holding variables and have that bean as a local variable in each class that needs them, where you were going to use abstract inheritance. This conforms to the pattern of composition , which is a more lightweight alternative to inheritance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM