开发者

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

开发者 https://www.devze.com 2023-01-21 22:53 出处:网络
Effective java says \"Consider providing static factory methods instead of constructors\" If you have开发者_开发问答 a

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.


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.).


For your example above it doesn't make much sense to provide a static constructor. And normally when you provide a static constructor you should make the normal constructor private. Otherwise it is still possible to create an instance with the normal constructor.

I try to explain here with another example, when you could use static factory methods. One of the advantages is, that you can give the factory methods understandable names.

class Complex {

     public static Complex fromCartesian(double real, double imag) {
         return new Complex(real, imag);
     }

     public static Complex fromPolar(double modulus, double angle) {
         return new Complex(modulus * cos(angle), modulus * sin(angle));
     }

     private Complex(double a, double b) {
         //...
     }
}

 Complex c = Complex.fromPolar(1, pi)

Or another example would be the Singleton Pattern. There you wan't to provide only one instance. So this is the reason why you make the constructor private and create an own getInstance method where you make sure, that there is always just one instance available.

public class Singleton {

    private volatile static Singleton singleton;

    private Singleton() {

    }

    // synchronized keyword has been removed from here
    public static Singleton getSingleton() {
        if(singleton==null) {
            synchronized(Singleton.class){
                if(singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }

}

Factory Method Pattern Wikipedia


The Singleton pattern with static method calls are a better design if ur looking for a single instance.. because of the reentrant locking nature of static.. providing thread safety and also avoiding out-of-order writes..

0

精彩评论

暂无评论...
验证码 换一张
取 消