You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

java.util.Calendar为何是工厂方法设计模式的实例?

Why Java's 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:

  1. Product Interface/Abstract Class: The Calendar abstract class itself. It defines all the core calendar operations (like get(), set(), add()) that all concrete calendar implementations must follow. This acts exactly like the "product interface" in the classic Factory Method example.

  2. Concrete Products: Classes like GregorianCalendar, JapaneseImperialCalendar, and others that extend Calendar and implement its abstract methods for specific calendar systems. These are the concrete products the factory method creates.

  3. 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 Calendar subclass gets instantiated. You don't need to write new 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 JapaneseImperialCalendar instead of a GregorianCalendar.
    • It handles all the initialization logic (like setting the current time, timezone adjustments) so you don't have to.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 19:32:44