简体   繁体   中英

Is it poor design to declare a class abstract because it only has static members?

I have a class in my project that is used to load external resources (namely, images and audio files). This class only has a few members: HashMap fields for storing resources, and getImage(reference) , etc. methods for retrieving the resources.

I originally implemented the singleton pattern , but then I read some criticisms on the linked page, and considered using static members.

Long after happily deciding to implement all the class functionality statically, I was doing some code cleanup. While doing this, I realized that nothing was stopping me from instantiating this ResourceManager class. This led me to tag it with the abstract keyword.

I've never used abstract in this way before; I've only ever applied it more conventionally for an inheritance tree. I tried Googling uses and misuses of abstract , but all the resources I found seemed either less-than-trustworthy, or didn't advise against the use of abstract in this way:

Oracle's tutorial on abstract classes and methods.
Another site discussing the keyword.

Quote from the second link: "Its purpose is to serve purely as a parent of classes."

Is my new implementation conventional, forgivable, or just plain wrong?

You don't have to make it abstract, just make the constructor private . Abstract tells developers that this class is meant for extending, which is not the case in your example.

private ResourceManager() {
}

如果我是你,我只是隐藏这样的构造函数:

private ResourceManager() {}

Is it poor design to declare a class abstract because it only has static members?

Yes.

Make it final and provide it with only a private constructor.

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