java.util.Calendar为何是工厂方法设计模式的实例?
Calendar Class Fits the Factory Method Pattern Great question! Let's break this down by first recalling the core idea of the Factory Method Pattern, then connecting it to how Calendar works under the hood.
First, the Factory Method Pattern's key goal is to encapsulate the creation of objects so that the code using the product doesn't need to know exactly which concrete class it's instantiating. The pattern typically has:
- A product interface/abstract class defining the common behavior of all products
- Concrete product classes implementing/extending the product interface
- A factory method (either in an abstract creator class or a static method) that handles the logic of selecting and instantiating the right concrete product.
Now, let's map this to Calendar:
Product Interface/Abstract Class: The
Calendarabstract class itself. It defines all the core calendar operations (likeget(),set(),add()) that all concrete calendar implementations must follow. This acts exactly like the "product interface" in the classic Factory Method example.Concrete Products: Classes like
GregorianCalendar,JapaneseImperialCalendar, and others that extendCalendarand implement its abstract methods for specific calendar systems. These are the concrete products the factory method creates.The Factory Method:
Calendar.getInstance()is your factory method! Even though it's a static method (not part of a separate "creator" subclass hierarchy), it still fulfills the factory method's purpose:- It hides the details of which concrete
Calendarsubclass gets instantiated. You don't need to writenew GregorianCalendar()directly. - It uses system settings (timezone, locale) to decide which concrete product to create. For example, if your locale is set to Japan, it might return a
JapaneseImperialCalendarinstead of aGregorianCalendar. - It handles all the initialization logic (like setting the current time, timezone adjustments) so you don't have to.
- It hides the details of which concrete
You might be used to the classic Factory Method example where you have an abstract Creator class with concrete ConcreteCreator subclasses, but the pattern has flexible implementations. The static factory method approach used by Calendar is a common, simplified variant that still adheres to the pattern's core principle: separating object creation from object use.
In short: Calendar.getInstance() is the factory method that abstracts away the creation of concrete calendar instances, making Calendar a perfect example of the Factory Method Pattern in action.
内容的提问来源于stack exchange,提问作者user344563

