开发者

Why is PMF.java a 'final' class?

开发者 https://www.devze.com 2022-12-21 16:41 出处:网络
According to the App Engine docs, the PersistenceManagerFactory should only be created once in the application.

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.

0

精彩评论

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