Java实现构建者(Builder)模式

本文介绍了一种设计模式——Builder模式,该模式适用于需要多步骤初始化复杂对象的情况。通过一个具体的Student类实例展示了如何使用Builder模式替代多参数构造函数,提高了代码的可读性和可维护性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Builder模式的定义是用于构建复杂对象的一种模式,所构建的对象往往需要多步初始化或赋值才能完成。那么,在实际的开发过程中,我们哪些地方适合用到Builder模式呢?其中使用Builder模式来替代多参数构造函数是一个比较好的实践法则。
我们有时候会写这样的实现类:

Student();
Student(String name);
Student(String name,int age);
Student(String name,int age,String address);
Student(String name,int age,String address,String id);

在实际开发中,我们有时候需要声明所有的构造方法,这样书写很常见并且也比较有效率,但是也存在很多不足,对于代码后期维护和协同开发会是一件很痛苦的事情。Builder模式就是使用一个代理完成对象的构建过程。这样的好处是易于扩展和类的使用,但同时也失去了一些效率。

/**
 * Created by Jackie on 2019/3/27.
 */
public class Student {
    private String name;
    private int age;
    private String address;
    private String id;

    private Student(Builder builder) {
        this.name = builder.name;
        this.age = builder.age;
        this.address = builder.address;
        this.id = builder.id;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String getAddress() {
        return address;
    }

    public String getId() {
        return id;
    }

    public static class Builder {
        private String name = null;
        private int age = 0;
        private String address = null;
        private String id = null;

        public Builder() {

        }

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

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

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

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

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

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

用法:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值