As of today, Xiaoqiu has been learning Java for just three months. At the moment pelle feel Java learning is good, want to go to handsome to show off in front of some, so, there was a dialogue…..

Proud little Autumn

Handsome: Hi, Xiaoqiu, look you look good today. How is your Java learning recently?

To be honest, this Java is so much friendlier than when I was learning Pointers three months ago. It just feels like a separate thing.

Handsome ground: I depend, you this tone return quite big. From c procedural oriented to Java object-oriented, are you used to it?

Xiaoqiu: Well, it’s just “everything is an object”. Objects in Java feel similar to structures in C. Anyway, it’s only three and twenty, and I think of them as objects in my mind. (Feeling good inside)

Handsome ground: see you also learned 3 months, otherwise I literally take a topic to take an examination of you? (Makes you laugh to yourself)

Pelle: Ok, good time to practice my skills.

A constructor that is overloaded multiple times

Handsome to: if there is a Cake Cake object, the object has a Cake will choose attribute size, there are also some optional attribute apple, banana, orange, mango, etc., shall be selected property on behalf of the user must specify the size of the Cake, optional attributes represent these cakes to add what materials.

Small autumn: this is very simple, to create a Cake, there are size, apple, banana, orange, mango attribute, then the size of the parameters specified in the constructor parameters. I’ll go straight to the code:

public class Cake {
    private int size;
    private String apple;
    private String banana;
    private String orange;
    private String mango;
    // Size must be given when new
    public Cake(int size) {
        this.size = size; }}Copy the code

Shuai: What about optional parameters? I want a new size=30, and add apple cake what to do?

Pelle: Oh, I wrote so fast THAT I forgot to reload. Hold on.

public class Cake {
    private int size;
    private String apple;
    private String banana;
    private String orange;
    private String mango;

    public Cake(int size) {
        this.size = size;
    }
    public Cake(int size, String apple) {
        this.size = size;
        this.apple = apple;
    }
    public Cake(int size, String apple, String orange) {
        this.size = size;
        this.apple = apple;
        this.orange = orange;
    }
    public Cake(int size, String apple, String orange, String mango) {
        this.size = size;
        this.apple = apple;
        this.orange = orange;
        this.mango = mango; }}Copy the code

Pelle: Well, I guess that’s all right. You use whatever you want. It’s all reloaded for you.

Shuai :(slyly) writing constructors is pretty fast, but what if I want to add apple and mango cakes only?

Pelle: Huh? Okay, you’re forcing me to write down all the constructors for all the combinations.

So, Pelle wrote out all the combinations of constructors. Since size is a mandatory parameter, combine the other four optional parameters to make a total of 16.

Crackling, splitting crackling, Pelle one breath to write them all out

public class Cake {
    private int size;
    private String apple;
    private String banana;
    private String orange;
    private String mango;
    
    public Cake(int size){
        this.size = size;
    }
    public Cake(int size, String apple){
        this.size = size;
        this.apple = apple;
    }
    public Cake(int size, String banana){
        this.size = size;
        this.banana = banana; }... }Copy the code

Pelle: Okay, now you can have any combination you want.

Shuai: four optional parameters you write a lot of parameters. Are you sure?

Xiao Qiu: I think it’s pretty good. Anyway, it’s fast. I’ll write as many as I can.

Shuai: What if you were given six optional parameters?

At this time Xiaoqiu secretly calculated some, found a total of 74 combinations?

Pelle: It’s just 74 combinations. I don’t think it’s a big deal.

Shuai: What if there are 10 optional parameters?

Small autumn:…

And you overload so many constructors that when the user is in new, what does the first argument and the second argument represent? For example, you have an Apple +banana constructor

public Cake(int size, String apple, String banana){
    this.size = size;
    this.apple = apple;
    this.banana = banana;
}
Copy the code

But the user may forget the order of the arguments when they are new

Cake cake = newCake (size, "banana", "apple").Copy the code

Pelle: I will provide the corresponding documentation. I forgot to look at the documentation.

Handsome: hundreds of constructors, and still so similar, you go to the documentation to try, and then say your mood.

Small autumn:…… (at a loss).

Through Javabean patterns

Shuaidi: have no other what method?

Pelle: I have another idea. I can set the optional parameters by using the set and get methods. I’ll go straight to the code

public class Cake {
    private int size;
    private String apple;
    private String banana;
    private String orange;
    private String mango;

    public Cake(int size) {
        this.size = size;
    }
    // Add material through set
    public void setApple(String apple) {
        this.apple = apple;
    }

    public void setBanana(String banana) {
        this.banana = banana;
    }

    public void setMango(String mango) {
        this.mango = mango;
    }

    public void setOrange(String orange) {
        this.orange = orange; }}Copy the code

At this time the pelle a little complacent….

Shuadi: pretty good. this method is much better than the previous one, and simple.

If you want to create a new apple+ Orange + Mango cake, the code is as follows:

Cake cake = new Cake(30);
cake.setApple("apple");
cake.setOrange("orange");
cake.setMange("mange");
Copy the code
Parameter dependency check problem

Shuadi: There are drawbacks to this approach, for example, it takes four lines of code instead of one line of code when reloading with a constructor.

Pelle: I think it’s nice anyway. .

Shuadi: but there is a fatal drawback to this writing. what if there is a dependency between those attributes? For example, Cake has two more attributes, A and B, and the two attributes are dependent on each other. If you set property A, but not property B, the Cake object will have A problem. Or the sequencing of attributes can cause problems. In this case, where do you check the logic of interdependence?

Little autumn: a little blind, at a loss…. .

Pelle: What do you suggest?

Static inner class

Shuadi: You’ve done a pretty good job, but I’ll show you another way. We can open up a static inner class to interact with the outside world, to collect the properties that the user wants to set and check them. Directly on the code:

public class Cake {
    private int size;
    private String apple;
    private String banana;
    private String orange;
    private String mango;
    //private, so that the outside can not create directly
    private Cake(Builer builer) {
        this.size = builer.size;
        this.apple = builer.apple; . }// It is used to communicate with the outside world
    public static class Builer {
        private int size;
        private String apple;
        private String banana;
        private String orange;
        private String mango;
        public void setSize(int size) {
            this.size = size;
        }
        // To save some code, the rest is omitted
        public Cake build(a) {
            // Check the dependencies between parameters
            return new Cake(this); }... }}Copy the code

Let’s say I want a new apple+orange Cake

Cake.Builer builer = new Cake.Builer();
builer.setSize(30);
builer.setApple("apple");
builer.setOrange("orange");
// Create a cake
Cake cake = builer.build();
Copy the code

Handsome ground: this kind of method cow? This is not enough, we can also use the method of chain call.

Chain calls
public class Cake {
    private int size;
    private String apple;
    private String banana;
    private String orange;
    private String mango;
    //private, so that the outside can not create directly
    private Cake(Builer builer) {
        this.size = builer.size;
        this.apple = builer.apple; . }// It is used to communicate with the outside world
    public static class Builer {
        private int size;
        private String apple;
        private String banana;
        private String orange;
        private String mango;
        // Change the return argument to Builer
        public Builer setSize(int size) {
            this.size = size;
            return this;
        }

        public Builer setApple(String apple) {
            this.apple = apple;
            return this;
        }
        // To save some code, the rest is omitted
        public Cake build(a) {
            // Check the dependencies between parameters
            return new Cake(this); }}}Copy the code

How to use it?

Cake cake = new Cake.Builer()
            .setSize(30)
            .setApple("apple")
            .setOrange("orange")
            .build();
Copy the code

One line of code.

Handsome ground: fierce?

It seems that I am still too young. I have to learn from Shuaidi.

Builder model

Shuai: Actually, the above method is one of the 23 design patterns – the Builder pattern. But this is a simplified version of the Builder model.

For the Builder pattern, the concrete UML diagram looks like this:

In this UML diagram, Builder is an interface that defines a set of specifications. In our example, we use concrete classes instead of interfaces, but the core idea is the same.

The idea is to separate the construction of a complex object from its representation, so that the same construction process can create different representations.

Xiao Qiu: Wow, strong. I’m going to like you…..

This is the second time to take a dialogue to write…. , will take this way to write more in the future.

After the

Pay attention to the public my number: helpless and painful code farmers, get more original articles, backstage reply gift package to send you a popular resource gift package. Also thanks for introducing the article to more people who need it