Java: static abstract (again) - best practice how to work around

后端 未结 9 1104
误落风尘
误落风尘 2021-02-01 16:30

I theoretically understand the point why there is no abstract static in Java, as explained for instance in Why can't static methods be abstract in

相关标签:
9条回答
  • 2021-02-01 17:13

    You could create a FileMetadata class that has all the info you need. When your app starts up, you could create instances of FileMetadata, and keep static pointers to them so you can access them from anywhere in the JVM.

    This way you put the abstract stuff in the actual instances; anything the stuff that does not call for abstract semantics can be static...

    0 讨论(0)
  • 2021-02-01 17:24

    This sounds like a great time to pull out the Fundamental Theorem of Software Engineering:

    Any problem can be solved by adding another layer of indirection.

    The problem you have right here is that a file carries around multiple pieces of information - what the type of the file is, a description of the file, the file contents, etc. I'd suggest splitting this into two classes - one class representing a concrete file on disk and its contents, and a second that is an abstract description of some file type. This would allow you to treat the file type class polymorphically. For example:

    public interface FileType {
         String getExtension();
         String getDescription();
    
         /* ... etc. ... */
    }
    

    Now, you can make subclasses for each of the file types you use:

    public class TextFileType implements FileType {
         public String getExtension() {
             return ".txt";
         }
         public String getDescription() {
             return "A plain ol' text file.";
         }
         /* ... */
    }
    

    You can then have some large repository of these sorts of objects, which would allow you to query their properties without having an open file of that type. You could also associate a type with each actual file you use by just having it store a FileType reference.

    0 讨论(0)
  • 2021-02-01 17:26

    Sounds like you need to use a singleton. Basically, you call a static method like MyFileTypes.getDataFileInstance() which creates a single instance (or reuses if already created) of an object and when you first create it setup the 'constants' as needed. I'll see if I can find you a good example but your post isn't very clear about how you want to use it.

    0 讨论(0)
提交回复
热议问题