SoFunction
Updated on 2025-03-08

Java uses static factories instead of constructor usage methods and advantages and disadvantages

1. Form

Copy the codeThe code is as follows:

public static Boolean valueOf(boolean b) {
    return b ? : ;
}

2. Advantages:

Can have a name
You don't have to create a new object, you can return an existing object
You can return objects of subclass type (example:)
Make the parameterized code shorter (example: change new HashMap<String,List<String>>() to () )

3. Disadvantages: It cannot be subclassed and cannot be recognized by IDE tools.

4. Common names: valueOf/of; getInstance(Singleton); newInstance; getType (used for different classes); newType