设计模式之建造者模式

设计模式 Java About 1,310 words

作用

用原型实例指定创建对象的种类,并且通过拷贝这些原型来创建新的对象。

案例

通过User.Builder类构建User。

User user = User.builder().name("张三").age(20).city("SH").build();

class User {

    private String name;
    private int age;
    private String city;

    public User(String name, int age, String city) {
        this.name = name;
        this.age = age;
        this.city = city;
    }

    public static User.Builder builder() {
        return new Builder();
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", city='" + city + '\'' +
                '}';
    }

    static class Builder {

        private String name;
        private int age;
        private String city;

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

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

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

        public User build() {
            return new User(this.name, this.age, this.city);
        }

    }

}

源码

java.lang.AbstractStringBuilder#append(java.lang.String)

AbstractStringBuilder是抽象类不能实例化,所以使用StringBuilder来充当Builder角色。

Views: 2,162 · Posted: 2019-12-16

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh