设计模式-建造者模式

1.概念

建造者模式(builder模式,属于创建型模式):通过将复杂对象的构建过程分解为多个步骤,使得对象的构建更加灵活和可控。

它适用于构建复杂对象,特别是当对象的构建过程涉及多个可选部分

2.Demo

1.创建一个匿名内部类Builder,其属性与外部类的属性相同;

2.将外部类的构造方法私有化(private),使用内部类填充属性;

3.在外部类创建builder()方法;

4.在内部类创建builder()方法。

public class Student{

    private int id;
    private String name;
    private int age;

    // 1 构建匿名内部类, 属性与Student类属性一致
    public static class Builder {
        private int id;
        private String name;
        private int age;

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

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

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

        // 4 最终构建返回
        public Student build() {
            return new Student(this);
        }
    }

    // 2 创建静态builder方法,返回Builder类进行构造
    public static Builder builder() {
        return new Builder();
    }

    // 3 构造私有构造方法,将Builder中的属性进行赋值
    private Student(Builder builder) {
        this.id = builder.id;
        this.name = builder.name;
        this.age = builder.age;
    }

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

测试类:

public class Main {
    public static void main(String[] args) {
        Student student = Student.builder()
                .id(1)
                .age(12)
                .name("李三")
                .build();
        System.out.println(student);
    }
}

结果输出:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值