class="java" name="code"> /** * Person Builder Test * @author Administrator * @date 2015-4-18 * @time 上午11:21:15 * @version 1.0 */ public class Person { private String id; private String name; private String password; private String phone; private String mail; private String address; /**无参构造器*/ public Person() { } /**builder模式构造器*/ public Person(PersonBuilder build){ this.id = build.id; this.name = build.name; this.password = build.password; this.phone = build.phone; this.mail = build.mail; this.address = build.address; } /**定义person的builder*/ public static class PersonBuilder{ private String id; private String name; private String password; private String phone; private String mail; private String address; public static PersonBuilder newBuilder(){ return new PersonBuilder(); } public Person build(){ return new Person(this); } public PersonBuilder id(String id) { this.id = id; return this; } public PersonBuilder name(String name) { this.name = name; return this; } public PersonBuilder password(String password) { this.password = password; return this; } public PersonBuilder phone(String phone) { this.phone = phone; return this; } public PersonBuilder mail(String mail) { this.mail = mail; return this; } public PersonBuilder address(String address) { this.address = address; return this; } } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getMail() { return mail; } public void setMail(String mail) { this.mail = mail; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } //测试 public static void main(String[] args) { //使用起来特别方便,但可以用传统的构造器,按个人喜好!!! Person p = PersonBuilder.newBuilder().id("123").name("abc").mail("dabc@163.com").build(); System.out.println(p.getName()); } }