Why is PMF.java a 'final' class?
According to the App Engine docs, the PersistenceManagerFactory
should only be created once in the application.
It provides this sample:
package guestbook;
import javax.jdo.JDOH开发者_StackOverflowelper;
import javax.jdo.PersistenceManagerFactory;
public final class PMF {
private static final PersistenceManagerFactory pmfInstance =
JDOHelper.getPersistenceManagerFactory("transactions-optional");
private PMF() {}
public static PersistenceManagerFactory get() {
return pmfInstance;
}
}
Why does PMF.java
have to be a "public final class
" in addition to making the pmfInstance
a "private static final
" object?
Classes should be final unless there's a good reason for them not to be.
There is no use case in which one would want to inherit from the PMF, so it should be final.
PMF is a class that should not be instantiated, since it has no instance state or methods, it is strictly there to provide static methods and global state.
Item 4 in Effective Java provides this idiom, however it does not add that the class should be made final, as it would be impossible to subclass it anyway with a private constructor. And there it is explicitly recommended that the private constructor be documented to avoid exactly the confusion you are having.
In addition, this code sample is providing the Static Initialization workaround for double check locking.
精彩评论