一:类的创建和销毁__构建器builder和javaBean

来源:互联网 发布:ie8 js兼容性问题 编辑:程序博客网 时间:2024/06/07 00:39

解决静态工厂和构造函数不能很好的扩展大量的可选参数,采用如下的两个方案解决

javaBean:

通过无参构造实例化一个对象,在调用setter方法来设定每一个必要/可选参数


构建器builder(只在很多参数才使用)

public class Student {// 必要参数private final int age;private final String sex;// 可选参数private final int tall;private final String name;// 构造函数private Student(Bulider bulider) {age = bulider.age;sex = bulider.sex;tall = bulider.tall;name = bulider.name;}/* * 构建bulidre类 */public static class Bulider {// 必要参数private final int age;private final String sex;// 可选参数private int tall = 0;private String name = "";public Bulider(int age, String sex) {this.age = age;this.sex = sex;}/** * 对可选参数进行构建 */public Bulider tall(int tall) {this.tall = tall;return this;}public Bulider name(String name) {this.name = name;return this;}// 返回构建的实例,关联student类public Student bulid() {return new Student(this);}}}使用:Student student = new Student.Bulider(20, "男").bulid();Student student = new Student.Bulider(20, "男").tall(150).bulid();


原创粉丝点击