Examples of GoF Design Patterns in Java's core libraries
There are many examples of the GoF (Gang of Four) design patterns in the core libraries of Java. Here are some examples:
- Factory Method: The
java.util.Calendar
class uses the Factory Method pattern to create instances ofCalendar
for a specific locale. ThegetInstance()
method is a factory method that creates and returns aCalendar
object for the default or specified locale.
Calendar calendar = Calendar.getInstance(); // Creates a Calendar for the default locale
- Abstract Factory: The
javax.xml.parsers.DocumentBuilderFactory
class uses the Abstract Factory pattern to create instances ofDocumentBuilder
that can be used to parse XML documents. ThenewInstance()
method is a factory method that creates and returns aDocumentBuilderFactory
object, and thenewDocumentBuilder()
method is a factory method that creates and returns aDocumentBuilder
object.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
- Builder: The
java.lang.StringBuilder
class uses the Builder pattern to create strings from multiple parts. Theappend()
method is used to add characters or strings to theStringBuilder
, and thetoString()
method is used to create aString
from the contents of theStringBuilder
.
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
String str = sb.toString();
- Singleton: The
java.lang.Runtime
class is a Singleton, because it provides a global access point to the runtime system and ensures that only one instance of the runtime is created. ThegetRuntime()
method is a factory method that returns the single instance of theRuntime
class.
Runtime runtime = Runtime.getRuntime();
These are just a few examples of the GoF design patterns in the core libraries of Java. There are many other examples of these and other design patterns in the libraries, as well as in the code that you can write in Java.