Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "Static factory methods" instead of constructors?

Tags:

Effective java says "Consider providing static factory methods instead of constructors"

If you have a

 class A {

     public static A getInstance() {
        return new A();
     }
 }

Does it make sense to provide this method for class A , rather than call new A() in the code.

like image 614
kal Avatar asked Oct 27 '10 02:10

kal


People also ask

Can factory methods be static?

A static factory method is a public static method on the object that returns a new instance of the object. These type of methods share the same benefits as the traditional factory method design pattern. This is especially useful for value objects that don't have a separate interface and implementation class.

What is the advantage of using a static factory method instead of a constructor to create an object?

One advantage of static factory methods is that, unlike constructors, they have names. If the parameters to a constructor do not, in and of themselves, describe the object being returned, a static factory with a well-chosen name is easier to use and the resulting client code easier to read.

Why would one use the factory method rather than just using a constructor?

The factory method is a smart way to create objects in Java and provides several advantages over the traditional approach of creating objects using constructors in Java. It can also improve the quality of code by making the code more readable, less coupled, and improves performance by caching.

What is one of the benefits of using static factory methods?

Advantages: One advantage of static factory methods is that, unlike constructors, they have names. A second advantage of static factory methods is that, unlike constructors, they are not required to create a new object each time they're invoked.


1 Answers

See here for a nice exposition of the main reasons you might want to do this. In summary:

  1. Named "constructors".
  2. Can return null, if appropriate.
  3. Can return an instance of a derived class, if appropriate.
  4. Reduce verbosity when instantiating variables of generic types.

Another reason comes to mind that the article doesn't mention: Can implement interesting logic to avoid creating new objects all the time (caching based on parameters, recycling, etc.).

like image 158
Marcelo Cantos Avatar answered Oct 09 '22 15:10

Marcelo Cantos