When to use Single method Interfaces in Java

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

    Favor Composition over Inheritance tutorial of Head First Design Pattern book recommends this approach to add functionality dynamically to a class. Let's take below case:

    public interface Quackable {
       public void quack();
    } 
    
    public class Quacks implements Quackable {
       public void quack(){
           //quack behavior
       }
    }
    
    public class DontQuack implements Quackable {
         public void quack(){
             //dont quack
        }
    }
    
    public class QuackableDuck{
        Quackable quack;  //add behavior dynamicall
    
    }
    

    So QuackableDuck class can add feature dynamically.

       quack = new Quacks();
       //or 
       quack = new DontQuack();
    

    So similarly you can add multiple behavior to the class dynamically.

提交回复
热议问题