简体   繁体   中英

Effective Java Item1 - Static factory method for object creation

I was going through Effective java item 1, where "Static factory method vs constructors" for object creation is discussed. One of the disadvantages mentioned is the following:

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

It is also mentioned that this is good since it will promote object composition to inheritance. However, is it not a serious limitation, when you indeed want inheritance? Why should I prefer static factory methods for object creation, when I do not know from before if the class is going to be extended or not?

Why should I prefer static factory methods for object creation, when I do not know from before if the class is going to be extended or not?

The answer to this question is in Effective Java Item 17: Design and Document for Inheritance or else Prohibit It . Designing a class for inheritance requires significantly more work, including the following.

  1. Documenting precisely the effects of overriding any method.
  2. Providing hook methods.
  3. Testing subclasses (by implementing those classes yourself).
  4. Restricting constructors to avoid all overridable methods.
  5. Considering the Cloneable and Serializable interfaces, and their effects on inheritance.

If you have done all of this work, then you will not provide only static factory methods. You will also provide at least one public or protected constructor.

Effective Java goes into detail on each of these points, but the final advice is,

The best solution to this problem is to prohibit subclassing in classes that are not designed and documented to be safely subclassed.

The quote is:

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

Not of static factories, but of providing only static factory methods , feel the difference.

You have to design for extension, not for "well, maybe I am not quite sure now, but I'll leave it extensible just in case".

If your class is extensible then it'll need at least a public constructor. In this case you can provide only static factory methods. But I won't call it a serious limitation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM