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.Calendarclass uses the Factory Method pattern to create instances ofCalendarfor a specific locale. ThegetInstance()method is a factory method that creates and returns aCalendarobject for the default or specified locale.
Calendar calendar = Calendar.getInstance(); // Creates a Calendar for the default locale- Abstract Factory: The
javax.xml.parsers.DocumentBuilderFactoryclass uses the Abstract Factory pattern to create instances ofDocumentBuilderthat can be used to parse XML documents. ThenewInstance()method is a factory method that creates and returns aDocumentBuilderFactoryobject, and thenewDocumentBuilder()method is a factory method that creates and returns aDocumentBuilderobject.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();- Builder: The
java.lang.StringBuilderclass 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 aStringfrom the contents of theStringBuilder.
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
String str = sb.toString();- Singleton: The
java.lang.Runtimeclass 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 theRuntimeclass.
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.