Java 单例类和静态类的区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3714971/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 03:50:34  来源:igfitidea点击:

Difference between singleton class and static class?

javastaticsingleton

提问by giri

Possible Duplicates:
Difference between static class and singleton pattern?
What is the difference between a Singleton pattern and a static class in Java?

可能的重复:
静态类和单例模式之间的区别?
Java 中的单例模式和静态类有什么区别?

HI I am not clearly getting What's the difference between a singleton class and a static class? Can anybody elaborate this with example?

嗨,我不清楚单例类和静态类有什么区别?有人可以举例说明这一点吗?

回答by oditiwebs.com

It's the difference between a pattern and how the pattern is implemented.

这是模式和模式的实现方式之间的区别。

The Singleton pattern is not tied specifically to the Java language. There may be different ways of making a class into a singleton, depending on the language you use. Many OO languages use the equivalent of static variables to make a singleton, but others might use different techniques.

单例模式与 Java 语言无关。根据您使用的语言,可能有不同的方法将类变成单例。许多 OO 语言使用等效的静态变量来创建单例,但其他语言可能使用不同的技术。

Also, some ways of implementing a singleton are better than others. One good way of implementing a Singleton is to properly encapsulate access to that Singleton through a factory method:

此外,实现单例的某些方法比其他方法更好。实现 Singleton 的一种好方法是通过工厂方法正确封装对该 Singleton 的访问:

public class Example {
    private static final Example SINGLETON = new Example();

    public static Example getInstance() { return SINGLETON; }

    private Example() { /* Constructor */ }
}

Using this technique, you can do all sorts of sophisticated things: lazy-load the singleton, replace it with some subclass, manage the singletons initialation via configuration, and so forth.

使用这种技术,你可以做各种复杂的事情:延迟加载单例,用一些子类替换它,通过配置管理单例初始化,等等。

回答by Andreas Dolk

A Singletonis not a type of a class but a design pattern. With Singletonyou (try to) guarantee, that only one instance of a certain class is ever constructed inside a single Java Virtual Machine. Modern implementations of the singleton pattern use enums, by the way. Older implementations use a private constructor and store the reference to the single instance in a static field.

辛格尔顿不是一个类型的一类,但设计模式。使用Singleton,您(尝试)保证在单个 Java 虚拟机中只构建了某个类的一个实例。顺便说一下,单例模式的现代实现使用枚举。较旧的实现使用私有构造函数并将对单个实例的引用存储在静态字段中。

A static classis always a member class which, in contrast to an inner class, has no access to instance variables of the surrounding class.

静态类始终是一个构件类,相对于内部类,具有与周围类的实例变量的访问权限。



Static class example

静态类示例

public class A {
  public static class B {        
  }     
  public        int notAccessibleForB;
  public static int    accessibleForB;
}

Singleton pattern (simple old style)

单例模式(简单的旧样式)

public final class Singleton {
  public final static Singleton INSTANCE = new Singleton();
  private Singleton(){}
}

Singleton pattern (simple modern style)

Singleton 图案(简约现代风格)

public enum Singleton {
   INSTANCE;
}

回答by Pranay Rana

Old que/ans on SO : Difference between static class and singleton pattern?

SO上的旧问题/答案:静态类和单例模式之间的区别?

A static class is one that has only static methods, for which a better word would be "functions". The design style embodied in a static class is purely procedural.

静态类是只有静态方法的类,对于这种方法更好的词是“函数”。静态类中体现的设计风格纯粹是程序性的。

Singleton, on the other hand, is a pattern specific to OO design. It is an instance of an object (with all the possibilities inherent in that, such as polymorphism), with a creation procedure that ensures that there is only ever one instance of that particular role over its entire lifetime.

另一方面,Singleton 是一种特定于 OO 设计的模式。它是一个对象的实例(具有其中固有的所有可能性,例如多态性),其创建过程可确保在其整个生命周期中只有一个特定角色的实例。

回答by YoK

Singleton Class: Singleton Class is class of which only single instance can exists per classloader.

单例类:单例类是每个类加载器只能存在单个实例的类。

Static/Helper Class (Class with only static fields/methods): No instance of this class exists. Only fields and methods can be directly accessed as constants or helper methods.

静态/助手类(只有静态字段/方法的类):不存在此类的实例。只有字段和方法可以作为常量或辅助方法直接访问。

Following is referenced from this blog "Static classes in Java"describes it nicely. The blog also has examples for explaining same:

以下是从这个博客引用的Java 中的静态类很好地描述了它。该博客还提供了解释相同内容的示例:

Singletonexample:

例示例:

public class ClassicSingleton {
    private static ClassicSingleton instance = null;

    private ClassicSingleton() {
        // Exists only to defeat instantiation.
    }

    public static ClassicSingleton getInstance() {
        if (instance == null) {
            instance = new ClassicSingleton();
        }
        return instance;
    }
}

Static Classexample:

静态类示例:

/**
 * A helper class with useful static utility functions.
 */
public final class ActionHelper {

    /**
     * private constructor to stop people instantiating it.
     */
    private ActionHelper() {
        // this is never run
    }

    /**
     * prints hello world and then the users name
     * 
     * @param users
     *            name
     */
    public static void printHelloWorld(final String name) {
        System.out.println("Hello World its " + name);
    }

}

So what's the difference between the two examples and why do I think the second solution is better for a class you don't want or need to instantiate. Firstly the Singleton pattern is very useful if you want to create one instance of a class. For my helper class we don't really want to instantiate any copy's of the class. The reason why you shouldn't use a Singleton class is because for this helper class we don't use any variables. The singleton class would be useful if it contained a set of variables that we wanted only one set of and the methods used those variables but in our helper class we don't use any variables apart from the ones passed in (which we make final). For this reason I don't believe we want a singleton Instance because we do not want any variables and we don't want anyone instantianting this class. So if you don't want anyone instantiating the class, which is normally if you have some kind of helper/utils class then I use the what I call the static class, a class with a private constructor and only consists of Static methods without any any variables.

那么这两个示例之间有什么区别,为什么我认为第二个解决方案更适合您不想或不需要实例化的类。首先,如果您想创建一个类的实例,单例模式非常有用。对于我的助手类,我们真的不想实例化该类的任何副本。不应该使用 Singleton 类的原因是因为对于这个辅助类,我们不使用任何变量。如果单例类包含一组我们只想要一组变量并且方法使用这些变量,但在我们的助手类中,除了传入的变量(我们将其设为 final)之外,我们不使用任何变量,那么它会很有用. 出于这个原因,我不相信我们想要一个单例实例,因为我们不想要任何变量而且我们不想要 不希望任何人实例化这个类。因此,如果您不希望任何人实例化该类,通常情况下,如果您有某种帮助程序/实用程序类,那么我使用我所说的静态类,一个具有私有构造函数的类,仅由静态方法组成,没有任何任何变量。

Same answer is also referenced from my answer here

同样的答案也引用自我的答案here

回答by Dead Programmer

The difference is not the correct way to ask.because singleton is not a keyword compared to static. you should be asking like "When to choose which one?". what are the advantages of singleton class over static class, these questions comes at the design stages.

区别不是询问的正确方法。因为与静态相比,单例不是关键字。你应该问“什么时候选择哪一个?”。单例类相对于静态类的优势是什么,这些问题出现在设计阶段。

Singleton: Usage: classes that serve as global configuration , ex: Trial version of software with one database connection, JDK Runtime classes instances per jvm.

单例:用法:用作全局配置的类,例如:具有一个数据库连接的软件的试用版,每个 jvm 的 JDK 运行时类实例。

When to go: 1.While developing your code,you think of forward compatibilty, like tomorrow when you need to convert this singleton class to normal class or allow subclassing. 2. You can provide lazy loading feature , when this singleton class is heavy.

何时开始: 1.在开发代码时,您会考虑向前兼容性,就像明天需要将此单例类转换为普通类或允许子类化一样。2.当这个单例类很重时,您可以提供延迟加载功能。

static: Usage: classes that basically does conversions,utility functions. please check Math class.

静态:用法:基本上进行转换的类,实用功能。请检查数学课。

When to go: 1. helper classes, used by all the classes in your api development.

何时使用: 1. 辅助类,由您的 api 开发中的所有类使用。

disadvantage: 1. classes are eagerly loaded .

缺点: 1. 类是急切加载的。

expecting points from other people.

期待别人的分数。