JAVA学习之Builder模式

来源:互联网 发布:算法公倍数怎么求 编辑:程序博客网 时间:2024/05/29 11:19

Builder模式原理,通过静态内部类来构建目标类
好处:
1.需要什么属性就填写什么属性,不需要为不同的实例来构建不同的构造函数
2.链式写法

package com.free.framwork.jdk8.builder;import java.util.Date;/** * com.free.framwork.jdk8.builder.Student * Builder模式 * @author lipeng * @dateTime 2017/8/26 12:17 */public class Student {    private Integer id;    private String name;    private Integer age;    private Date birthday;    private Student(Builder builder) {        this.id = builder.id;        this.name = builder.name;        this.age = builder.age;        this.birthday = builder.birthday;    }    @Override    public String toString() {        return "Student{" +                "id=" + id +                ", name='" + name + '\'' +                ", age=" + age +                ", birthday=" + birthday +                '}';    }    public static class Builder{        private Integer id;        private String name;        private Integer age;        private Date birthday;        // 构建Builder对象        public static Builder builder() {            return new Builder();        }        public Builder id(Integer id){            this.id = id;            return this;        }        public Builder name(String name){            this.name = name;            return this;        }        public Builder age(Integer age){            this.age = age;            return this;        }        public Builder birthday(Date birthday){            this.birthday = birthday;            return this;        }        // 通过Builder对象来构建Student对象        public Student build(){            return new Student(this);        }    }}
package com.free.framwork.jdk8.builder;import java.util.Date;/** * com.free.framwork.jdk8.builder.TestBuilder * * @author lipeng * @dateTime 2017/8/26 12:25 */public class TestBuilder {    public static void main(String[] args) {        Student student = Student.Builder.builder()                .id(10001)                .name("测试")                .age(22)                .birthday(new Date())                .build();        Student student1 = Student.Builder.builder()                .id(10002)                .name("测试1")                .age(22)                .birthday(new Date())                .build();        System.out.println(student);        System.out.println("======================");        System.out.println(student1);    }}
原创粉丝点击