Skip to content

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 of Calendar for a specific locale. The getInstance() method is a factory method that creates and returns a Calendar object for the default or specified locale.

java
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 of DocumentBuilder that can be used to parse XML documents. The newInstance() method is a factory method that creates and returns a DocumentBuilderFactory object, and the newDocumentBuilder() method is a factory method that creates and returns a DocumentBuilder object.

java
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
  • Builder: The java.lang.StringBuilder class uses the Builder pattern to create strings from multiple parts. The append() method is used to add characters or strings to the StringBuilder, and the toString() method is used to create a String from the contents of the StringBuilder.

java
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. The getRuntime() method is a factory method that returns the single instance of the Runtime class.

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

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.