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

后端 未结 9 1113
误落风尘
误落风尘 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: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.

提交回复
热议问题