Java构建器模式尝试

一、Student包含构建器类

创建Student类,包含StudentBuilder构建器,替代Student的构造方法:

package cays.build;

/**
 * 学生类
 * @create 2020/1/7
 **/
public class Student {
    private String name;
    private String nick;
    private String password;
    private double score;
    private int age;
    private String gender;

    private Student(StudentBuilder builder) {
        this.name = builder.name;
        this.nick = builder.nick;
        this.password = builder.password;
        this.score = builder.score;
        this.age = builder.age;
        this.gender = builder.gender;
    }

    public static class StudentBuilder {
        private String name;
        private String nick;
        private String password;
        private double score;
        private int age;
        private String gender;
        public StudentBuilder() {

        }

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

        public StudentBuilder setNick(String nick) {
            this.nick = nick;
            return this;
        }

        public StudentBuilder setPassword(String password) {
            this.password = password;
            return this;
        }

        public StudentBuilder setScore(double score) {
            this.score = score;
            return this;
        }

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

        public StudentBuilder setGender(String gender) {
            this.gender = gender;
            return this;
        }

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

    @Override
    public String toString() {
        return "姓名:" + name + ",昵称:" + nick + ",密码:" + password + ",分数:" + score + ",年龄:" + age + ",性别:" + gender;
    }

    public String getName() {
        return name;
    }

    public String getNick() {
        return nick;
    }

    public String getPassword() {
        return password;
    }

    public double getScore() {
        return score;
    }

    public int getAge() {
        return age;
    }

    public String getGender() {
        return gender;
    }
}

二、测试构建器

测试一下:

package cays.build;

/**
 * 测试Java构建器模式
 * @create 2020/1/7
 **/
public class StudentBuilderMain {
    public static void main(String[] args) {
        Student student = new Student.StudentBuilder().setName("a")
                .setNick("b")
                .setPassword("ccc")
                .build();
        System.out.println(student.toString());
        Student student1 = new Student.StudentBuilder().setName("b").setAge(13).build();
        System.out.println(student1.toString());
    }
}

三、测试结果

测试结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值