When to use Single method Interfaces in Java

前端 未结 5 770
无人及你
无人及你 2021-02-01 04:50

I have seen in many libraries like Spring which use a lot of interfaces with single methods in them like BeanNameAware, etc.

5条回答
  •  遇见更好的自我
    2021-02-01 05:36

    Interfaces with only one (or few) methods is the key to the highly useful Strategy pattern, which is "some design standard which advocates the use of these type of interfaces".

    Another common scenario is when you want a callback. Foo calls Bar as an asynchronous task, and when Bar is finished with something, the result is sent back to Foo using a callback -- which can be an interface containing only one method. (An example of this is the many listeners in Android, Event Listeners in Swing...)

    Also, if you have two classes that are tightly coupled with one another (let's call them Foo and Bar). Foo uses nearly all of Bar's methods, but Bar only needs some a few of those from Foo. Foo can implement FooInterface which is then sent to Bar. Now the coupling is looser, because Bar only knows about the FooInterface, but does not care about the other methods the implementing class contains.

提交回复
热议问题