打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
建造者模式之项目运用

1 问题

建造者模式,我们也许不陌生,因为我们看到很多开源框架或者Android源码里面用到,类似这样的代码结构

A a = new A.builder().method1("111").method2("222").build();

很明显,一般这里的结构有builder()构造函数,还有build()函数,主要用来干嘛呢?还不是为了构建对象,如果需要设置的参数很多的话,一个一个去set很繁琐也不好看,下面有个例子简单粗暴展示。 

2 测试代码实现

package com.example.test1;

public class Student {
    private int id;
    private String name;
    private int age;
    private String classNmae;

    public Student(Builder builder) {
        this.id = builder.id;
        this.name = builder.name;
        this.age = builder.age;
        this.classNmae = builder.classNmae;
    }
    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String getClassNmae() {
        return classNmae;
    }

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

    public static class Builder {
        private int id;
        private String name;
        private int age;
        private String classNmae;

        public Builder() {}
        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;
        }
        public Builder className(String classNmae) {
            this.classNmae = classNmae;
            return this;
        }
        public Student build() {
            return new Student(this);
        }
    }
}
                Student student = new Student.Builder()
                .name("chenyu")
                .age(28)
                .id(1)
                .className("erzhong")
                .build();
        Log.i(TAG, "student toString is:" + student.toString());

 

 

3 运行结果

18376-18376/com.example.test1 I/chenyu: student toString is:Student{id=1, name='chenyu', age=28, classNmae='erzhong'}

 

 

 

 

 

 



4 总结

1)我们需要构建一个对象很多参数的时候用这种方式

2)最关键的是需要构建的对象类里面有个Builder类作为参数传递

    public Student(Builder builder) {
        this.id = builder.id;
        this.name = builder.name;
        this.age = builder.age;
        this.classNmae = builder.classNmae;
    }

3)最后build()函数里面返回的是需要构建的类本身

        public Student build() {
            return new Student(this);
        }
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
78条高质量编码建议《Effective Java》(1~2)阅读笔记
008
Java封装与构造方法——致敬周老师
Student
设计模式之建造者模式(C++)
博客园 - 探索设计模式(四):建造者模式过程图解(Builder Pattern)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服