Effective Java -- Create and destroy objects -- 1-5 items

  • Static Factory Method

Interpretation: A common static method defined in a class returns an instance of the class (either the class itself or another class).

Advantages:

  1. Static factory methods can have names
  2. Static factory methods differ from constructors in that they do not have to create a new object every time they are called
  3. Static factory method can return any subtype of the original return type
  4. The class of the object returned by the static factory method can change with each call
  5. The class to which the object returned by the method belongs may not exist when writing a class containing the static factory method.

Points 2-5 are a bit verbose and far-fetched. Constructors are meant to construct instances of classes, so the return type of constructors is limited, which is not a pity. The static factory method is actually a common static method, of course, it can return any type. However, the first advantage mentioned by the static factory approach relative to the constructor generation instance is that it's much better to have names.

For the following class, it is not possible to write an initialized bb constructor that takes an int as a parameter, because the function type is distinguished by the parameter type, not by the parameter name.

public Class A{
    int aa = 0;
    int bb = 0;
    public A(int tmp){
        aa = tmp;
        bb = 0;
    }
}

So you can use the static factory method to instantiate classes directly through different function commands, as follows:

public Class A{
    int aa = 0;
    int bb = 0;
    private static final DEAINSTANCE = new A(0,0);
    private A(int aa, int bb){
        aa = aa;
        bb = bb;
    }

    //This static method can be used to modify the value of aa
    public static A newAwithaa(int aa){
        retuan new A(aa, 0);
    }

    //This static method can be used to modify the value of bb
    public static A newAwithbb(int bb){
        retuan new A(0, bb);
    }

    //This static method takes a default instance without reconstructing a new object
    public static A getInstance(){
        return DEAINSTANCE;
    }

}

The common names of static factory methods are listed below:

From -- Type conversion method, from A instance to B instance

Of - - - aggregation method, aggregation of multiple parameters, generation of new instances

valueOf -- a more cumbersome alternative to from and of

instance/getInstance - Returns different instances based on the entry (if any)

Create / new Instance -- Returns different new instances based on the entry (if any)

getType -- similar to getInstance

New Type -- Similar to New Instance

  • Builder

Background: When multiple constructor parameters are encountered, the general overlapping constructor pattern can lead to confusion. The constructor function has the same name and only different parameters. If there are five parameters, the constructor of the pattern will have at least five, which is confusing and inconvenient to use. The use of Java beans pattern can solve this confusion to some extent, but it breaks the initialization process of the instance. It may call the method of set ting a parameter between the first and second use of the same instance, resulting in the fact that the instance is different; moreover, JavaBeans pattern makes it possible to make the class immutable. Sex no longer exists.

Interpretation: Instead of directly generating the desired object, the builder lets the client invoke the constructor (or static factory) with all the necessary parameters to get a builder object. The client then invokes a setter-like method on the builder object to set each relevant optional parameter. Finally, the client calls the parametric build method to generate normally immutable objects.

The following code is an example of a builder pattern:

Builder is an internal class of the class to be constructed. The Builder class has all the attributes of the class. Each attribute provides a method for setting and setting the return type of the method to Builder. This feature makes it possible to call various setup functions in a chain. At the end of the chain, a parametric build function is used to construct the class. The build function returns the constructor of a class. The constructor's input is an instance of the Builder.

public class NutritionFacts {
    private final int servingSize;
    private final int servings;
    private final int calories;

    public static class Builder {
        private final int servingSize;
        private final int servings;
        private int calories = 0;

        public Builder(int servingSize, int servings){
            this.servingSize = servingSize;
            this.servings = servings;
        }

        public Builder calories(int val){
            this.calories = val;
            return this;
        }

        public  NutritionFacts build(){
            return new NutritionFacts(this);
        }
    }

    private NutritionFacts(Builder builder){
        servingSize = builder.servingSize;
        servings = builder.servings;
        calories = builder.calories;
    }

    public static void main(String[] args) {
        NutritionFacts cocaCola = new Builder(5, 20).calories(5).build();
    }
}

 

  • Private constructor
  • Priority for Dependency Injection

 

Keywords: Java Attribute

Added by jplush76 on Sun, 18 Aug 2019 17:24:06 +0300