建造者模式

这也是一种创建型模式

使用场景

一个类有多个构造函数的时候,可以考虑使用建造者模式

我的 demo

package com.carl.builderdemo;

public class User {

    private String name;
    private String color;
    private String vegetable;
    private String nik;
    private int age;
    private String language;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getVegetable() {
        return vegetable;
    }

    public void setVegetable(String vegetable) {
        this.vegetable = vegetable;
    }

    public String getNik() {
        return nik;
    }

    public void setNik(String nik) {
        this.nik = nik;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getLanguage() {
        return language;
    }

    public void setLanguage(String language) {
        this.language = language;
    }

    private User(Builder builder) {
        this.name = builder.name;
        this.color = builder.color;
        this.vegetable = builder.vegetable;
        this.nik = builder.nik;
        this.age = builder.age;
        this.language = builder.language;
    }

    public static class Builder {
        private String name;
        private String color;
        private String vegetable;
        private String nik;
        private int age;
        private String language;

        public Builder() {
            name = "carl";
            color = "blue";
            vegetable = "rou";
            nik = "carl";
            age = 28;
            language = "Chinese";
        }

        public Builder uName(String name) {
            this.name = name;
            return this;
        }

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

        public Builder uVegetable(String vegetable) {
            this.vegetable = vegetable;
            return this;
        }

        public Builder uNik(String nik) {
            this.nik = nik;
            return this;
        }

        public Builder uAge(int age) {
            this.age = age;
            return this;
        }

        public Builder uLanguage(String language) {
            this.language = language;
            return this;
        }

        public User Build() {
            return new User(this);
        }
    }
}

测试类

package com.carl.builderdemo;

public class Test {

    public static void main(String[] args) {
        User u = new User.Builder().uAge(20).Build();
        System.out.println(u.getAge());
        System.out.println(u.getName());
    }

}

我的理解

它使用了内部类的方式,将原来自己的类方法变成私有的,
而后提供一个静态的内部类来创建对象
另外通过返回 this 对象来链式调用
本类同时为对象提供了一个默认值
最后想说看十遍,不如手写一遍


↙↙↙阅读原文可查看相关链接,并与作者交流