java jdk中工厂模式的示例

时间:2012-09-25 23:25:19

标签: factory-pattern

在以下链接: Examples of GoF Design Patterns in Java's core libraries java.lang.Object #toString()是工厂模式的示例。 我很困惑。 到目前为止我所理解的是工厂模式用于创建对象。 有人能更清楚地解释一下吗?

2 个答案:

答案 0 :(得分:1)

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

我们有:

抽象类或接口:对象

构建方法:toString()

实现:任何java对象

产品:字符串

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

答案 1 :(得分:0)

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

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