Java中Builder设计模式用法分享
下文笔者讲述Builder设计模式简介如下所示
Builder设计模式简介
主要用于解决对象构建比较的复杂的情况 如: 构造超出构造函数的表示,此时我们可以使用Builder模式, 使构建变的简单明了 Builder设计模式的实现思路: 只需在Set属性时,返回当前对象 使用此种模式,即可实现Builder设计模式例:
Student实体定义
package com.java265.model; 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 + '}'; } }
Builder设计模式的使用示例
package com.java265.model; import java.util.Arrays; public class TestStudent { public static void main(String[] args) { Student s = new Student.Builder() .name("java265") .age(22) .language(Arrays.asList("chinese","english")) .build(); //Student{name='java265', age=22, language=[chinese, english]} System.out.println(s); // Classic way to create an object /* Student s = new Student(); s.setName("java265"); s.setAge(22); s.setLanguage(Arrays.asList("chinese","english")); */ } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。