啥叫建造者模式?
就是说需要搞的这个玩意儿比较复杂,您要是一趟车就要搞定,貌似难度比较大。那咋办,你得像建大楼一样,一层层往上盖才行。或者说你得先从小零件搞起,然后慢慢组装,最后成为成品。
举个例子:假如你要生产一台计算机(假设你有能力生产所有部件),那你得先搞个CPU吧,然后再得搞个主板吧(主板上你得搞这种芯片吧),然后你觉得显示效果不爽,你还得搞个显卡吧,然后电源啦,硬盘啦,机箱啦,显示器啦等等等等,折腾了这么多,你搞出一台计算机来。
再比如某机构要登记信息系统的用户信息,一个用户,首先有姓名,年龄,电话,地址,身份证号码,然后名族,是否已婚,学历,家里几口人,种了几亩田,名下有几套房产…吧啦吧啦…等等相关信息,组装起来就是用户。
拼装好了,最后“啪”贴个封条(就是Build方法),就可以出货啦!
貌似看出点意思了,一句话,拼装呗!这时候建造者模式的作用就来了,下面就是代码示例:
package com.creational.builder;
public class User
{
//All final attributes
private final String firstName; // required
private final String lastName; // required
private final int age; // optional
private final String phone; // optional
private final String address; // optional
private User(UserBuilder builder) {
this.firstName = builder.firstName;
this.lastName = builder.lastName;
this.age = builder.age;
this.phone = builder.phone;
this.address = builder.address;
}
//All getter, and NO setter to provde immutability
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getPhone() {
return phone;
}
public String getAddress() {
return address;
}
@Override
public String toString() {
return "User: "+this.firstName+", "+this.lastName+", "+this.age+", "+this.phone+", "+this.address;
}
public static class UserBuilder
{
private final String firstName;
private final String lastName;
private int age;
private String phone;
private String address;
public UserBuilder(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public UserBuilder age(int age) {
this.age = age;
return this;
}
public UserBuilder phone(String phone) {
this.phone = phone;
return this;
}
public UserBuilder address(String address) {
this.address = address;
return this;
}
//Return the finally consrcuted User object
public User build() {
User user = new User(this);
validateUserObject(user);
return user;
}
private void validateUserObject(User user) {
//Do some basic validations to check
//if user object does not break any assumption of system
/*if(user.age <= 0){
throw new IllegalArgumentException();
}*/
}
}
}
package com.creational.builder;
public class TestUserBuilder {
public static void main(String[] args) {
User user1 = new User.UserBuilder("Lokesh", "Gupta")
.age(30)
.phone("1234567")
.address("Fake address 1234")
.build();
System.out.println(user1);
User user2 = new User.UserBuilder("Jack", "Reacher")
.age(40)
.phone("5655")
//no address
.build();
System.out.println(user2);
User user3 = new User.UserBuilder("Super", "Man")
//No age
//No phone
//no address
.build();
System.out.println(user3);
}
}
以上代码很好懂,就不用多解释了,最后还是来张建造者的UML来调节一下:
参考文献:
https://github.com/ncsbalaji/DesignPaterns
http://www.cnblogs.com/beijiguangyong/archive/2010/11/15/2302807.html#_Toc281750449