What are static factory methods?

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

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

14条回答
  •  悲哀的现实
    2020-11-22 06:33

    If the constructor of a class is private then you cannot create an object for class from outside of it.

    class Test{
     int x, y;
     private Test(){
      .......
      .......
      }
    }
    

    We cannot create an object for above class from outside of it. So you cannot access x, y from outside of the class. Then what is the use of this class?
    Here is the Answer : FACTORY method.
    Add the below method in above class

    public static Test getObject(){
      return new Test();
    }
    

    So now you can create an object for this class from outside of it. Like the way...

    Test t = Test.getObject();
    

    Hence, a static method which returns the object of the class by executing its private constructor is called as FACTORY method
    .

提交回复
热议问题