6 commonly used design patterns for JDK class libraries in Java

Six commonly used design patterns for JDK class libraries in Java:1. Abstract factory. 2. Builder mode. 3. Factory mode. 4. Prototype mode. 5. Singleton mode. 6. Adapter mode.

1. Abstract Factory

  • javax.xml.parsers.DocumentBuilderFactory抽象类。

  • public static DocumentBuilderFactory newInstance()方法。

  • Class function: Allows applications to obtain a parser that can generate DOM objects through XML files.

  • Method function: Get a new instance of DocumentBuilderFactory. This static method creates a newfactory instance.

2. Builder mode

  • java.lang.StringBuilder, this is a final class.

  • public StringBuilder append(String str) method, this method isoverwriting of the parent class.

  • Class function: used foran unchangeable character sequence.

  • Method function: Based on the existing character sequence and appended characters, generate a new character sequence through the system copy methodSystem.arraycopy.

3. Factory mode

  • java.text.NumberFormat抽象类。

  • public final static NumberFormat getInstance()方法。

  • Class Function: Abstract base class for number format.

  • Method function: Return a NumberFormat of "auniversal number format in the current default scenario." Obviously it belongs to the use of factory mode.

4. Prototype mode

  • java.lang.Object

  • protected native Object clone() method

  • Class function:The parent class of all classes.

  • Method function: Return ashallow copy object based on the existing instance.

5. Singleton mode

  • java.lang.RunTime

  • public static Runtime getRuntime()

  • Class function: Each running java application will have aunique instance of the RunTime class , this instance enables the application to be affected by the running environment during runtime.

  • Method function: Return a RunTime object associated with the current java application.

6. Adapter mode

  • java.util.Arrays

  • public static List asList(T… a) method.

  • Class functions: This class contains a large number ofmethods for operating on arrays.

  • Method function: Convert an array of reference type into a List. Therefore, you can use List class operations to operate array objects, but there is one thing to note: cannot use add(), remove() operations, because the return The bottom layer of the list is based on an array, and the array structure cannot be changed. The list class is the adapter here. Through this adapter, direct operations on the array become indirect operations.

Guess you like

Origin blog.csdn.net/qq_30713721/article/details/134899541