02. An excessive use of builder mode configuration parameters

Foreword

"Effective Java" Chinese third edition, is a book about the basics of Java, this book was recommended to me more than once. Including my favorite garden blog blogger CJ May , he worked in his blog "to the Java program apes recommend some good books worth a visit" also been recommended. Deepen their memories, while in line to good people, decided after reading each chapter, write an essay. If you have to write the wrong place, where unclear statements, or other suggestions, I hope you can correct me message, thank you.

"Effective Java" Chinese third edition Read online links: https://github.com/sjsdfg/effective-java-3rd-chinese/tree/master/docs/notes

 

What is

builder mode is a way to create objects. There is a common way to create an object model JavaBeans, scalable method mode.

 

Where use

Many optional parameters to extend the scene, "a lot of optional parameters" means that when you reach such construction methods to the Senate when four or more.

When an entity class, and you're convinced it will add a new field in the latter, you can also use pre-builder mode, because you did not use a start in the latter part of the class parameter to the time evolution out of control, think of into builder mode, before I wrote the code would be useless.

 

How to achieve

We JavaBeans model, scalable method mode creates Builder schema objects, a method of comparison, take a look at to achieve Builder, as well as its advantages.

First, let's consider a scenario, a bottle of beverage, its main raw material there are many, such as vitamins, water, sugar and so on. We first use mode scalable method to realize such a class code as follows:

public class Drink {

    // water required parameter 
    Private  Final  int Water;

    // sugar required parameter 
    Private  Final  int Sweet;

    // vitamin optional parameter 
    Private  Final  int Vitamins;

    // beverage bottle color optional parameter 
    Private  Final String Color;

    public Drink(int water, int sweet){
        this(water, sweet, 0);
    }

    public Drink(int water, int sweet, int vitamins){
        this(water, sweet, 0, "白色");
    }

    public Drink(int water, int sweet, int vitamins, String color){
        this.water = water;
        this.sweet = sweet;
        this.vitamins = vitamins;
        this.color = color;
    }

    public static void main(String[] args) {
        Drink wowHaHa = new Drink(0, 0);
    }


}

 

When we want to create an object, you can at least into the reference method used to create a constructor (the example above a minimum of two arguments: water, sugar to create a Drink class). In general, the method can create scalable method mode lets you pass something that you do not want to set the parameters, but you have to pass a value for them. The example above (only) four attributes to the Senate, may seem not so bad, if there are ten, twenty it? That it will soon be out of control.

Briefly, scalable model construction method when there are many parameters, it is difficult to write code for the client, but it is difficult to read. 

In order to solve the 'many parameters' question (constructors encountered a number of optional parameters), we Another option is to use JavaBeans model, in this mode, call a no-argument constructor to create the object, then call the  setter method to set each of the required and optional parameters, the following sample code:

public  class Drink02 {
     // water required parameter 
    Private  int Water;

    // sugar required parameter 
    Private  int Sweet;

    // vitamin optional parameter 
    Private  int Vitamins = -1 ;

    // beverage bottle color optional parameter 
    Private String Color = "white" ;
    
    public Drink02(){ }
    
    //Setters
    public void setWater(int val) {water = val;}
    public void setSweet(int val) {sweet = val;}
    public void setVitamins(int val) {vitamins = val;}
    public void setColor(String val) {color = val;}

    // create an object model using JavaBeans
     public  static  void main (String [] args) {
        Drink02 waHaHa = new Drink02();
        waHaHa.setWater ( 300 );
        waHaHa.setSweet(10);
        waHaHa.setVitamins ( . 1 );
        waHaHa.setColor ( "black bottle" );
    }
}

JavaBeans mode, the method without the disadvantages scalable mode, but the code looks somewhat lengthy, but it is convenient to create an instance, and the generated code more readable.

However, JavaBeans model is seriously flawed, since the method of construction is divided into a number of calls, so the setting properties (during construction) the JavaBean may be in an inconsistent state. This class is not to force the consistency of options by checking the validity of configuration parameters parameters. Try to use an object in an inconsistent state may cause some errors. For example, a need to set up a mandatory parameter, but we did not set up. Fortunately, we have a third option: Builder mode, the code examples are as follows:

public  class Drink03 {
     // water required parameter 
    Private  Final  int Water;

    // sugar required parameter 
    Private  Final  int Sweet;

    // vitamin optional parameter 
    Private  Final  int Vitamins;

    // beverage bottle color optional parameter 
    Private  Final String Color;

    public static class Builder {
        private final int water;

        private final int sweet;

        private int vitamins = 0;

        private String color = "白色";

        public Builder(int water, int sweet){
            this.water = water;
            this.sweet = sweet;
        }

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

        public Builder color(String val){
            color = val;
            return this;
        }

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

    private Drink03(Builder builder){
        water    = builder.water;
        sweet    = builder.sweet;
        vitamins = builder.vitamins;
        color    = builder.color;
    }


    // create an object using the pattern Builder 
    public  static  void main (String [] args) {
         new new Builder (100,10 )
                .vitamins(1).color("黑色").build();
    }
}

Because all the default parameters are in one place, so our Drink03 objects are immutable, setter assignment operation, we builder process has been completed, we will be chained calls. This code is very easy to write when you create an object, but also easy to read.

 

to sum up

Builder to create an object model

advantage:

  • More flexible. Builder flexible selection optional parameters may be automatically filled mandatory parameter.
  • safer.

Disadvantages:

  • To create an object, you must first create its builder. This may be a problem in the performance of a fancy occasion. Moreover, builder mode is more verbose than stretching constructor mode, it is sufficient if the parameters are in use worth it.

In conclusion, when designing class constructor or static parameters of more than a few plants, Builder mode is a good choice, especially if many parameters are the same or alternative type. client code pattern builder than a telescopic construction method is easier to read and write, and safer than the builder pattern JavaBeans.

Guess you like

Origin www.cnblogs.com/gongguowei01/p/12159168.html