简体   繁体   English

系统 class singleton 是抽象的还是什么?

[英]Is System class singleton, abstract or what?

A class like LocalDate is immutable, it has a private constructor and each time we want an object of it, we have to call it's static methods, like LocalDate.now() or LocalDate.of(year, month, day) .LocalDate这样的 class 是不可变的,它有一个私有构造函数,每次我们想要一个 object 时,我们都必须调用它的 ZA81259CEF8E959C624DF1D456E5D, LocalDate.now()LocalDate.of(year, month, day)方法。 These methods use new keyword and call that private constructor, so each time a "new reference" is created.这些方法使用new关键字并调用该私有构造函数,因此每次都会创建一个“新引用”。 It is not a singleton class because we can have multiple objects at the same time.它不是 singleton class 因为我们可以同时拥有多个对象。

But what about System class?但是System class 呢? It looks like LocalDate , it has a private constructor, but it doesn't have a static method to call that.它看起来像LocalDate ,它有一个私有构造函数,但它没有 static 方法来调用它。 This class, also is not abstract, so why java programmers wrote System class like nobody can make an object of it?这个 class 也不是抽象的,那为什么 java 程序员写System class 就像没有人可以制作 ZA8CFDE6331BD59EB2666ZFC 一样? What is the design pattern behind it?它背后的设计模式是什么? Which classes act like this?哪些类是这样的?

It has a private constructor which is never called, so there are never any instances (singleton would require one).它有一个从不调用的私有构造函数,因此永远不会有任何实例(单例需要一个)。

/** Don't let anyone instantiate this class */
private System() {
}

It is not abstract它不是抽象的

public final class System {

System is used more like a namespace. System更像是一个命名空间。 It's just a container for a bunch of static methods and constants.它只是一堆 static 方法和常量的容器。

Java does not allow you to put methods outside of a class so sometimes the result is a completely uninstantiated "class" like this. Java 不允许您将方法放在 class 之外,因此有时结果是像这样完全没有实例化的“类”。

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

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