What is the advantage of using Supplier in Java?

后端 未结 1 1756
北恋
北恋 2021-02-19 11:02

Reading about the new Supplier interface I can\'t see any advantage of its usage. We can see bellow an example of it.

class Vehicle{
  public void drive(){ 
             


        
相关标签:
1条回答
  • 2021-02-19 11:49

    In your example above I'd not use a supplier. You are taking a Vehicle to drive, not requesting vehicles.

    However to answer your general question:

    • Because building a car is expensive and we don't want to do it until we really really need to.
    • Because we want X cars not just one.
    • Because the time of construction for a car is important.
    • Because construction is complicated so we want to wrap it up.
    • Because we don't know which Vehicle to return until we return it (maybe it will be a new one, maybe a recycled one, maybe a wrapper, who knows)
    0 讨论(0)
提交回复
热议问题