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?
-
1Seems like a weak example to me. – BillRobertson42 Sep 25 '12 at 23:32
-
@Bill..Yes, that's why I wanted to be clear whether something I am not getting or this example itself is not correct. Can you provide a strong example in jdk? – AKS Sep 25 '12 at 23:44
-
Yes, the Factory pattern is very generic... which is why GoF only lists "Factory method" and "Abstract Factory", no generic "Factory" pattern ;) – Richard JP Le Guen Sep 26 '12 at 00:05
-
possible duplicate of [Factory, Abstract Factory and Factory Method](http://stackoverflow.com/questions/2079902/factory-abstract-factory-and-factory-method) – Richard JP Le Guen Sep 26 '12 at 00:05
2 Answers
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.

- 373
- 1
- 15
-
then in that case..any method of any interface, except having void return type can be classified as factory pattern.. right? – AKS Sep 25 '12 at 23:48
-
Yeah, exactly. That's pretty much why I think it's a silly example. – dakotapearl Sep 29 '12 at 23:07
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

- 867
- 9
- 21