Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

The normal way for a class to allow a client to obtain an instance is to provide a public contructor. Another way to do that is providing a public static factory method, which is simply a static method that returns an instance of the class. What are pros and cons by using static factory method?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
365 views
Welcome To Ask or Share your Answers For Others

1 Answer

This chapter from the book Effective Java explains it well: Consider Static Factory instead of Constructors. It explains all the pros and cons for both of them in the best way you can understand.

Just to quote the advantages and disadvantages from the book:

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.
  • A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type.
  • A fourth advantage of static factory methods is that they reduce the verbosity of creating parameterized type instances (This one can be ignored in Java 7)

Disadvantages:

  • The main disadvantage of providing only static factory methods is that classes without public or protected constructors cannot be subclassed

  • A second disadvantage of static factory methods is that they are not readily distinguishable from other static methods.

You can study them in more detail in the link I gave.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...