创建模式-Builder

创建模式-Builder

Tags: Java 设计模式

摘要

创建模式-Builder

JavaBean对象

package cn.javacore.designpatterns;

import java.util.List;

public class Student {

    private String name;
    private int age;
    private List<String> language;

    public static class Builder {

        private String name;
        private int age;
        private List<String> language;

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

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

        public Builder language(List<String> language) {
            this.language = language;
            return this;
        }

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

    }

    private Student(Builder builder) {
        name = builder.name;
        age = builder.age;
        language = builder.language;
    }

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

测试

package cn.javacore.designpatterns;

import java.util.Arrays;

public class TestStudent {

    public static void main(String[] args) {

        Student s = new Student.Builder()
                .name("zhu")
                .age(18)
                .language(Arrays.asList("chinese", "english"))
                .build();

        //Student{name='zhu', age=18, language=[chinese, english]}
        System.out.println(s);

        // Classic way to create an object
        /*
        Student s = new Student();
        s.setName("zhu");
        s.setAge(18);
        s.setLanguage(Arrays.asList("chinese","english"));
        */

    }

}

解释

链式操作,非常方便,直观。

参考链接

https://en.wikipedia.org/wiki/Builder_pattern
http://www.javaworld.com/article/2074938/core-java/too-many-parameters-in-java-methods-part-3-builder-pattern.html

下载地址

https://coding.net/u/javacore/p/java-io-study/git/tree/master/src/main/java/cn/javacore/designpatterns