1

在下面的链接 中:Java 核心库中的 GoF 设计模式示例 java.lang.Object#toString() 是工厂模式的示例。我对此感到困惑。到目前为止我所了解的是工厂模式用于创建对象。有人可以更清楚地解释吗?

4

2 回答 2

2

本质上,工厂模式是一个抽象类或接口,它指定了一种生产方法。然后你有一个实现,并且从那个实现中,你可以构建那个东西

在这里,我们有:

抽象类或接口:对象

构建方法:toString()

实现:任何java对象

产品:一根绳子

所以,是的,这是一个奇怪的例子,还有更好的例子,但它确实适合工厂的模型。

于 2012-09-25T23:44:02.090 回答
0

当我们有一个具有多个子类的超类并且基于输入,我们需要返回一个子类时,使用工厂设计模式。通常,存在 getInstance() 方法,它根据提供的输入返回不同类型的对象。为了更好地理解它,您可以参考这个示例,在 Java API 中,calender 类根据输入返回不同的日历对象:

static Calendar getInstance()
Gets a calendar using the default time zone and locale.

static Calendar getInstance(Locale aLocale)
Gets a calendar using the default time zone and specified locale.

static Calendar getInstance(TimeZone zone)
Gets a calendar using the specified time zone and default locale.

static Calendar getInstance(TimeZone zone, Locale aLocale)
Gets a calendar with the specified time zone and locale.

JDK中使用的工厂模式示例:

java.util.Calendar, ResourceBundle and NumberFormat getInstance() methods

于 2019-07-03T13:22:32.523 回答