java 链式调用

来源:互联网 发布:网络公会白马义从 编辑:程序博客网 时间:2024/06/05 00:22

前言

现在很多开源库或者代码都会使用链式调用。因为链式调用在很多时候,都可以使我们的代码更加简洁易懂。以下 Student 类有多数个属性,让我们看看非链式调用和链式调用有何区别。

非链式调用

Main 类:

    /**     * Created by chenxuxu on 17-1-10.     */    public class Main {        public static void main(String[] args) {            Student stu = new Student();            stu.setAge(22);            stu.setName("chenxuxu");            stu.setGrade("13级");            stu.setNo("123456789");            stu.setMajor("软件工程");        }    }

Student 类:

    /**     * 学生类     *      * Created by chenxuxu on 17-1-10.     */    public class Student {        /**         * 姓名         */        private String name;        /**         * 年龄         */        private int age;        /**         * 学号         */        private String no;        /**         * 年级         */        private String grade;        /**         * 专业         */        private String major;        //...此处省略getter&setter    }

链式调用

Main 类:

    /**     * Created by chenxuxu on 17-1-10.     */    public class Main {        public static void main(String[] args) {            Student.builder()            .stuName("chenxuxu")            .stuAge(22)            .stuGrade("13级")            .stuMajor("软件工程")            .stuNo("123456789");        }    }

Student 类:

    /**     * 学生类     *      * Created by chenxuxu on 17-1-10.     */    public class Student {        /**         * 不能通过new初始化         */        private Student(){}        public static Builder builder(){            return new Builder();        }         static class Builder{            /**             * 姓名             */            private String name;            /**             * 年龄             */            private int age;            /**             * 学号             */            private String no;            /**             * 年级             */            private String grade;            /**             * 专业             */            private String major;            public Builder stuName(String name){                this.name = name;                return this;            }            public Builder stuAge(int age){                this.age = age;                return this;            }            public Builder stuNo(String no){                this.no = no;                return this;            }            public Builder stuGrade(String grade){                this.grade = grade;                return this;            }            public Builder stuMajor(String major){                this.major = major;                return this;            }        }    }

结论

通过链式调用后,代码看起来简洁易懂。

0 0
原创粉丝点击