About Generating a Java Instance

Asked 2 years ago, Updated 2 years ago, 31 views

Date = new Date();
Calendar c=Calendar.getInstance();

Both of the above generate instances, one with new and the other without.
Is the only way to judge this is to know how to use each class?
Please let me know if you know more.Thank you for your cooperation.

java

2022-09-30 20:47

2 Answers

It is true that you have no choice but to look at the reference and learn how to use each class, but it is designed according to design pattern, so if you know the pattern, you will understand it.

For example, the Calendar class cannot be abstract to create an instance with new Calendar().We actually use the derivative GregorianCalendar and Calendar.getInstance() returns the instance according to the running environment.This is a design pattern called Factory Method.

On the other hand, Date is just a value object, so you don't have to create a derivative instance.


2022-09-30 20:47

While Date is immutable, Calendar is not.If you implement operations such as 3 days plus 2 hours plus 35 minutes with an immutable object, you'll need a lot of wasted instances.Calendar can change itself, so you don't have to worry about it.Also, when you make additional changes to the locale, you can hide the implementation.


2022-09-30 20:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.