简体   繁体   中英

Is it possible for several classes to share an interface implementation?

I have a number of java classes that are already implemented. I would like to add some behavior to these classes; this behavior in some cases could be identical for all classes. It is also assumed that I can not create a super class since all the classes are already implemented.

The question I have is what options do I have in this regard.

Interface: Is it possible that for some interfaces I implement them once and have classes share the single implementation (since in some cases the implementation required would be identical for all classes). This would avoid manual duplication of code in all classes.

I thought about defining an abstract class and having the classes extend the abstract class; the problem is that the sublcasses would in this case would not be a meaningful extension of the abstract class since they do not form a meaningful hierarchy.

Thanks.

如果接口方法的实现不依赖于实现类的成员,并且您正在使用Java 8,则可以为接口的方法提供默认实现。

You can use the "delegation" pattern. Define a new interface with a method (or methods) defining the behavior you want to add, and an implementation class for each variant of the behavior. Have each of your existing classes reference an instance of whichever implementation class it needs. The wikipedia page for "Delegation Pattern" has some good simple examples in Java and other languages: https://en.wikipedia.org/wiki/Delegation_pattern

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