Builder模式

来源:互联网 发布:kontakt mac 音源入库 编辑:程序博客网 时间:2024/06/03 18:25

          Builder 模式主要用于如何 创建一个对象。例如,如果一个类有很多属性,比如说 : 

public class Teacher{    private String id;    private String name;    private String sex;    private String tel;    …….}

那么,我们有几种方法创建这个对象。
  1. 创建一个空对象,然后不停的 把属性 set 进去。
  2. 创建一个包含全部参数 的构造函数。new 对象的时候 就会变成如下形式:
    1. Teacher teacher = new Teacher(“1”,”tea”,”male”,”18620213358");

上面这两种方式都有一些缺点,第一种的话 set 过多。第二种的话可读性会不太足。

以下介绍 Builder 模式 创建 对象。代码如下: 
public class Teacher{    private String id;    private String name;    private String sex;    private String tel;    public Teacher(Builder builder){        this.id = builder.id;        this.name = builder.name;        this.sex = builder.sex;        this.tel = builder.tel;    }    public class Builder{        private String id;        private String name;        private String sex;        private String tel;        public Builder id(String id){            this.id = id;            return this;        }        public Builder name(String name){            this.name = name;            return this;        }        public Builder sex(String sex){            this.sex = sex;            return this;        }        public Builder tel(String tel){            this.tel = tel;            return this;        }        public Teacher build(){            return  new Teacher(this);        }     }}

这样,创建对象的时候就变成了:

Teacher tea = new Teacher.Builder().id(“1”).name(“tea”).sex(“male”).tel(“18620213358”).build();

可读性会变好点。也显得高大上点。




0 0
原创粉丝点击