I am reading Sierra/Bates chapter 6 on i18n, where 'tis explained that the instantiation of the 3 abstract classes util.Calendar, text.DateFormat and text.NumberFormat can only be done through static factory methods (get<Xxx>Instance()). The book does not elaborate further, and I don't blame them, still I'm curious...
What I am wondering about is why it is so. Does anybody know or can speculate why the abstract factory method pattern was chosen by the mythical Java API designers? Why should this design approach be deemed more suitable (I assume that it is?) than the good olde overloaded constructor approach, as with the old util.Date class?
BTW, I did google around on this subject, but online articles on this subject are rather dense, cryptic and too generalized; and I'm specifically curious about these 3 classes Calendar, DateFormat, NumberFormat. Perhaps some ranchers here can offer a brief explanation?
The abstract factory pattern is used for a lot of things, but its most important characteristic is that it hides the actual concrete implementation class from the client code. In other words, Calendar.getInstance() might actually give you an GregorianCalendar or AlGoreDoomsdayCalendar, but all you know is that you're getting some kind of Calendar. This pattern is very useful for promoting loose coupling, and it's used extensively in OO design.
Contrast this with direct instantiation, where the client code must know the exact concrete class.
Joined: Nov 15, 2007
Thanks Kelvin, that's a very nice explanation, and I am beginning to see the light.
Still I have some doubts... Loose coupling is paramount in OO, sure. But don't clients need to know exactly what type of Calendar instance they get and demand that they get it? In other words, what if I specifically must get the AlGoreDoomsdayCalendar -- but the Calendar.getInstance() method will not offer or guarantee it to me? How do I go about it then?
The factory pattern is used when the calling class does not know or does not need to know what concrete class will be instantiated or when the calling class does not know how to instantiate the concrete class. The Calendar API just tells you about the method getInstance: Returns: a Calendar.
If you know you need the special Al Gore doomsday calendar, you simply cannot use the getInstance method of class Calendar. You would have to instanciate the doomsday calendar on your own or - if the AlGore class is a factory as well - use their getInstance method.
To Silicon Oyster: Nice link. Please have a look into your private messages by clicking the "My Private Messages" link near the top of this page.
all events occur in real time
Joined: Nov 15, 2007
Thank you gentlemen! Your answers have cleared it up a lot. I get the picture now.
subject: Instantiation of abstract i18n classes using static factory methods