简体   繁体   English

使用静态类而不是单例模式?

[英]When use a static class instead of the singleton pattern?

我已经阅读了这个问题和一些类似的问题,我想知道是否有任何情况我应该在单例模式上使用静态类?

Use a static "utility" class (a class with nothing but static methods) when you have "just code" methods - methods where you don't need any particular implementation of a base class or interface. 方法,你不需要任何特定的实现基类或接口的-当你有“刚代码”方法使用一个静态的“工具”类(只是静态方法的类)。 The key indicator is that the code is stateless - ie there are no (static) fields in the class to give it state. 关键指标是代码是无状态的 - 即类中没有(静态)字段给它状态。 Being stateless also means the methods are automatically thread safe - another benefit. 无状态也意味着这些方法是自动线程安全的 - 另一个好处。

There are many examples in the JDK ( Collections being one notable example) and the apache commons libraries of this pattern working very well. JDK中有许多示例( Collections是一个值得注意的例子),并且这种模式的apache commons库运行良好。

Also, to avoid "class bloat", rather than have a class for a particular trivial implementation, you can have static (abstract) factory methods that return a particular implementation, for example: 此外,为了避免“类膨胀”,而不是为特定的简单实现提供类,您可以使用返回特定实现的静态(抽象)工厂方法,例如:

public static Comparator<String> createCaselessStringCompatator() {
    return new Comparator<String> () {
        public int compare(String o1, String o2) {
            return o1.toUpperCase().compareTo(o2.toUpperCase());
        }
    }; 
}

public static Comparator<String> createNumericStringCompatator() {
    return new Comparator<String> () {
        public int compare(String o1, String o2) {
            return new Double(o1).compareTo(new Double(o2));
        }
    }; 
}

This pattern avoids creating a whole new class file for what amounts to just a single line of actual useful code (ie a " closure ") and it bundles them up so if you know your utility class name, your IDE will prompt you for which impl you want to choose: 这种模式避免了创建一个全新的类文件,只需要一行实际有用的代码(即“ 闭包 ”) 并将它们捆绑在一起,所以如果你知道你的实用程序类名,你的IDE会提示你哪个impl你想选择:

Collections.sort(myStringList, MyComparators.|<-- ctrl+space to offer options

Whereas without this pattern, you'd have to remember the class name of each of the implementations. 而没有这种模式,你必须记住每个实现的类名。

我认为这将是一个需要一些实用功能的地方,这又是静态的。

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

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