AKS
AKS

Reputation: 1423

example of factory pattern in java jdk

At below link: Examples of GoF Design Patterns in Java's core libraries that java.lang.Object#toString() is example of factory pattern. I am confused about this. What i have understood till now is that factory pattern is used to create objects . Can someone explain it more clearly?

Upvotes: 1

Views: 4241

Answers (2)

user
user

Reputation: 977

Factory design pattern is used when we have a super class with multiple sub-classes and based on input, we need to return one of the sub-class. Typically, getInstance() method is present which returns different type of objects based on inputs provided. To understand it better, You can refer this example, in Java API- calender class returns different calender object based on inputs :

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.

Examples of Factory pattern used in JDK:

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

Upvotes: 2

dakotapearl
dakotapearl

Reputation: 373

In essence, the factory pattern is an abstract class or interface that specifies a method to produce something. Then you have an implementation and from that implementation, you can build that something.

Here we have:

Abstract class or interface: Object

Build method: toString()

Implementation: Any java object

Product: A string

So yeah, it is a bit of a strange example and there are better ones out there, but it does fit the model for a factory.

Upvotes: 2

Related Questions