Search code examples
factory-pattern

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?


Solution

  • 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.