简体   繁体   中英

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.

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:

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.

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

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