[英]Why does the Calendar class not have a public constructor?
Will new Calendar()
have any difference from Calendar.getInstance()
? 将
new Calendar()
有任何差别Calendar.getInstance()
The question is just as simple as it is........... Since the system refuse to post it, I just copy some nonsense here. 这个问题就这么简单...........由于系统拒绝发布它,因此我在这里复制了一些废话。
private static Calendar calendar = Calendar.getInstance();
public static int getCalendar(long time, int calendarConst) {
calendar.setTimeInMillis(time);
return calendar.get(calendarConst);
}
There is a detailed account of the difference between constructors and static factory methods in Effective Java second edition, which is well worth a read. 在Effective Java第二版中详细说明了构造函数和静态工厂方法之间的区别,非常值得一读。
The main difference here is in what the two return: 这里的主要区别在于两者的返回值:
The latter case is exactly what Calendar.getInstance()
does: you clearly don't get back an instance of Calendar
itself, since it is abstract, but instead you might get a GregorianCalendar
, JapaneseImperialCalendar
etc. 后一种情况正是
Calendar.getInstance()
所做的:由于它本身是抽象的,因此您显然不会返回Calendar
本身的实例,但是相反,您可能会得到GregorianCalendar
, JapaneseImperialCalendar
等。
This decouples Calendar
's implementation from the client code: you can make changes to Calendar
without the client needing to make changes. 这使
Calendar
的实现与客户端代码脱钩:您可以对Calendar
进行更改,而无需客户端进行更改。
When you do new Calendar()
, it creates new calendar instance from the default Calendar instance. 当您执行
new Calendar()
,它将根据默认的Calendar实例创建新的日历实例。 Sometimes creating an instance via constructor is not good as creating from Factory methods. 有时通过构造函数创建实例不如从Factory方法创建实例。 That's why it uses Factory methods to create an instance.
这就是为什么它使用Factory方法创建实例的原因。
And, 和,
Calendar.getInstance()
is a native method, and note down native methods don't have body/implementation. Calendar.getInstance()
是本机方法, 请注意本机方法没有正文/实现。 They have implemented already from the system. 他们已经从系统中实现了。
It writes here: https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html . 它写在这里: https : //www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html 。
And, as explained in above answers already, the calendar instance is created by calling Calendar class. 并且,正如上面答案中已经解释的那样,日历实例是通过调用Calendar类创建的。 Static Factory design pattern to create calendar instance.
用于创建日历实例的静态Factory设计模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.