简体   繁体   English

实用 class 替代私有 static 字段

[英]Utility class alternative for private static field

import java.io.File;

public final class MultiplatformUtility {
    private static final String SEPARATOR = File.separator;

    private MultiplatformUtility() { }

    public static String getSeparator() {
        return SEPARATOR;
    }
}

I want SEPARATOR to be in a unique file.我希望 SEPARATOR 在一个唯一的文件中。 Is there a way to avoid using a utility class here but maintain SEPARATOR field static and private?有没有办法避免在这里使用实用程序 class 但保持 SEPARATOR 字段 static 和私有?

Edit: How about a ENUM inside of a Class?编辑:Class 中的 ENUM 怎么样?

import java.io.File;

public class Multiplatform {

    public enum Common {
        SEPARATOR(File.separator);
    
        private final String separator;

        Common(final String separator) {
            this.separator = separator;
        }

        public String getSeparator() {
            return separator;
        }
    }
}

In my humble opinion, it doesn't make sense to make SEPARATOR as private , considering also that is a public member of java.io.File , so you are restricting the access qualifier of an already existing field.在我看来,将SEPARATOR设为private是没有意义的,同时考虑到它是java.io.Filepublic成员,因此您正在限制现有字段的访问限定符。 That is against the encapsulation and inheritance best practice.这违反了封装和 inheritance 最佳实践。

Bear in mind that when you make it private , only that class will have access to its value, unless you provide a specific method to get access to it, just as you did with MultiplatformUtility .请记住,当您将其设为private时,只有 class 才能访问其值,除非您提供特定的方法来访问它,就像您对MultiplatformUtility所做的那样。
As possible solution to your goal, you could have a public abstract class in a separated file, and make the field protected, so only the classes which extends your abstract class will have access to it.作为您的目标的可能解决方案,您可以在一个单独的文件中拥有一个public abstract class,并使该字段受到保护,因此只有扩展您的抽象 class 的类才能访问它。 Personally, this is NOT best practice.就个人而言,这不是最佳做法。

Normally, you define an interface and add all constants in it, so it can be used by all classes among your application, but in that case each constant will be by default public static final .通常,您定义一个interface并在其中添加所有常量,以便应用程序中的所有类都可以使用它,但在这种情况下,每个常量默认为public static final

Even better, you can define an enum in a sepated class, just as in your example, which gives you also more advantages than an interface as you get some utility functions by the fact that implicitly extends java.lang.Enum , plus you can define fields, methods and implement interfaces.更好的是,您可以在分隔的 class 中定义一个enum ,就像在您的示例中一样,这给您带来比接口更多的优势,因为您可以通过隐式扩展java.lang.Enum获得一些实用功能,另外您还可以定义字段、方法和实现接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM