Design Patterns of Java 1. Creation Pattern: Factory Method

The purpose of the factory method is to separate the created object and the used object, and the client always refers to the abstract factory and abstract product:

 1. Static factory method:

The static methods of the java standard library, such as: Integer.valueOf();

Integer is both a product and a static factory. It provides a static factory valueOf() to create an Integer;

public final class Integer {
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
    ...
}

The advantage is that the static factory method can be optimized internally, which can return a new instance of Integer, or directly return a cached Integer instance, saving resources. The factory method can hide the details of creating a product, and not necessarily create the product every time, it can return the cached product, thereby increasing the speed and reducing memory consumption. Static factory method List.of();
 List<String> list = List.of("A","B","C"); 
ArrayList<String> list = List.of("A","B", "C"); The product obtained by the caller is always the List interface, and does not care about the actual type, and can be modified to return java.ArrayList; this is the principle of Richter substitution: returning any subclass that implements the interface 
can meet the requirements of the method , And does not affect the caller. Always refer to the interface instead of the implementation class, which allows subclasses to be called without affecting the caller, and is as abstract programming as possible.








Guess you like

Origin blog.csdn.net/a159357445566/article/details/108587992