为什么我只能有一个 Calendar 对象实例
I was just wondering...
why can i have only one instance of Calendar object. Is there a reason for it to be a singleton?
I have tried to read the documentation but they didn't mention why this is needed. And a quick google search didn't give me any answers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Calendar 不是单例,它是一个抽象类。
getInstance
方法是一个返回 Calendar 类的具体实现的工厂方法。在 Google 中搜索 java.util.Calendar 源代码,您将看到它是如何工作的。
Calendar is not a singleton, it is an abstract class. The
getInstance
method is a Factory method that returns a concrete implementation of the Calendar class.Search Google for java.util.Calendar source code, and you will see how it works.
它不是单例。
这是:
输出:(
如您所见,这是不同的)
顺便说一句,快速搜索 源代码返回:
It is not singleton.
This:
Outputs:
(Which is different as you can see)
BTW, quick search for source code returns:
您是否认为它是单例,因为它有
getInstance()
方法?事实并非如此!getInstance()
每次都会返回一个新实例。Did you think that it is a singleton because it has a
getInstance()
method? That's not the case!getInstance()
returns a new instance each time.您可以根据需要拥有尽可能多的
Calendar
实例...以它是一个抽象类为模,因此您正在谈论 Calendar 的子类的实例。也许您认为
getInstance()
方法返回一个单例对象?事实并非如此。每次调用它时它都会创建并返回一个新对象。(javadoc 没有明确声明日历不是单例,但它说“返回的日历基于当前时间......”。这意味着它正在返回一个新对象每次......因为当前时间不断变化,无论如何,如果您想查看源代码,这就是该方法的作用。)
You can have as many instances of
Calendar
as you want ... modulo that it is an abstract class, so you are talking about of instances of child classes of Calendar.Perhaps you think that the
getInstance()
method returns a singleton object? It doesn't. It creates and returns a new object each time you call it.(The javadoc doesn't explicitly state that the calendar is not a singleton, but it says "The Calendar returned is based on the current time ...". That implies that it is returning a new object each time ... because the current time keeps changing. And anyway, that's what the method does if you'd care to look at the source code.)