What are static factory methods?

前端 未结 14 1154
粉色の甜心
粉色の甜心 2020-11-22 06:08

What\'s a \"static factory\" method?

14条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 06:25

    Readability can be improved by static factory methods:

    Compare

    public class Foo{
      public Foo(boolean withBar){
        //...
      }
    }
    
    //...
    
    // What exactly does this mean?
    Foo foo = new Foo(true);
    // You have to lookup the documentation to be sure.
    // Even if you remember that the boolean has something to do with a Bar
    // you might not remember whether it specified withBar or withoutBar.
    

    to

    public class Foo{
      public static Foo createWithBar(){
        //...
      }
    
      public static Foo createWithoutBar(){
        //...
      }
    }
    
    // ...
    
    // This is much easier to read!
    Foo foo = Foo.createWithBar();
    

提交回复
热议问题