When to use Single method Interfaces in Java

前端 未结 5 763
无人及你
无人及你 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:50

    In what scenarios does it make sense to keep single method interfaces?

    In such a scenarios when you need an interface with only one method.

    Interfaces are used to encapsulate a common behavior of several classes. So if you have several places in your code where you need to call only limited set of class methods, it's time to introduce an interface. The number of methods depends on what exactly do you need to call. Sometimes you need one method, sometimes two or more, sometimes you don't need methods at all. What matters is that you can separate behavior from implementation.

提交回复
热议问题