开发者

What would be a viable design alternative to nesting an interface inside a concrete class? [duplicate]

开发者 https://www.devze.com 2023-04-07 10:18 出处:网络
This question already has answers here: Why would a static nested interface be used in Java? (11 answers)
This question already has answers here: Why would a static nested interface be used in Java? (11 answers) Closed 9 years ago.

When I read about nesting an interface inside of a class, the intention appears to be to encapsulate the abstract behavior of the interface through composition. However, to me it makes more sense to create the interface outside the class, then use a getter/setter and return an instance of the interface type. There must be a benefit that I'm not seeing. Is this simply a matter of "choice开发者_StackOverflow".


If the interface strongly related with some class, it might be reasonable to nest it within the class. For example: SurfaceHolder.Callback which allows a client to receive information about changes to the surface in Android. The Callback interface is nested within the SurfaceHolder, and it is easier to access and find it within that context.

However, for generic interfaces such as Runnable which is implemented by a class whose instances to be executed by a thread, it is completely outside of a class (in the java.lang package for this example). This make more sense because, this interface could be used by any class, not necessarily within a specific context).


It is not a matter of choice if we talk about highly complex, scalable and re-usable systems. There are so named S.O.L.I.D. design principles (dependency injection and inversion of control if we talk specifically) which suppose the use of interfaces. The reasons to use them are:

1) the decoupling of the models inside your code. If you create the objects inside a class when your classes cannot be used in other projects as they are tightly coupled

2) possibility of creating mocks for right unit tests. You can test concrete layers, in your case by testing the highest level you invoke all the methods of the lower levels.

3) Interfaces can be combined and used throughout the whole system in many places so a lot of other classes can use the mailer server, for example

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号