What are static factory methods?

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

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

14条回答
  •  有刺的猬
    2020-11-22 06:52

    I thought i will add some light to this post on what i know. We used this technique extensively in our recent android project. Instead of creating objects using new operator you can also use static method to instantiate a class. Code listing:

    //instantiating a class using constructor
    Vinoth vin = new Vinoth(); 
    
    //instantiating the class using static method
    Class Vinoth{
      private Vinoth(){
      }
      // factory method to instantiate the class
      public static Vinoth getInstance(){
        if(someCondition)
            return new Vinoth();
      }
    }
    

    Static methods support conditional object creation: Each time you invoke a constructor an object will get created but you might not want that. suppose you want to check some condition only then you want to create a new object.You would not be creating a new instance of Vinoth each time, unless your condition is satisfied.

    Another example taken from Effective Java.

    public static Boolean valueOf(boolean b) {
            return (b ? TRUE : FALSE);
    }
    

    This method translates a boolean primitive value into a Boolean object reference. The Boolean.valueOf(boolean) method illustrates us, it never creates an object. The ability of static factory methods to return the same object from repeated invocations allows classes to maintain strict control over what instances exist at any time.

    Static factory methods is that, unlike constructors, they can return an object of any subtype of their return type. One application of this flexibility is that an API can return objects without making their classes public. Hiding implementation classes in this fashion leads to a very compact API.

    Calendar.getInstance() is a great example for the above, It creates depending on the locale a BuddhistCalendar, JapaneseImperialCalendar or by default one Georgian.

    Another example which i could think is Singleton pattern, where you make your constructors private create an own getInstance method where you make sure, that there is always just one instance available.

    public class Singleton{
        //initailzed during class loading
        private static final Singleton INSTANCE = new Singleton();
    
        //to prevent creating another instance of Singleton
        private Singleton(){}
    
        public static Singleton getSingleton(){
            return INSTANCE;
        }
    }
    

提交回复
热议问题