Builder模式

Builder模式有什么好处?
构造函数构造一个函数的好处就是直接,但是缺点就是如果参数比较多,需要重载构造函数或者一个构造函数里面定义多个构造参数,对于调用方来讲十分不友好;
另外一种方式就是java bean模式,定义一个简洁的构造函数,然后通过set属性的方式来构造;这种方式避免了构造函数模式的那种参数众多的丑陋,但是同时却也带来潜在并发问题,就是可能该对象还没有构造完成就被别的线程拿去用了。
这种模式的优势合并在一起,同时摒弃劣势就是Builder模式;既可以定义一个简洁的构造函数,同时还可以一次性的将对象构建完毕。
Server端代码:
 1 public class Dog {
 2     private final String name; // 名称
 3     private final String sex; // 性别
 4     private final int age; // 年龄
 5     private final String fur; // 毛发
 6     private final String breed; // 品种
 7     private final float weight; // 体重
 8     private final float height; // 身高
 9 
10     private Dog(Builder builder) { // 私有构造方法,入参为内部类对象
11         name = builder.name;
12         sex = builder.sex;
13         age = builder.age;
14         fur = builder.fur;
15         breed = builder.breed;
16         weight = builder.weight;
17         height = builder.height;
18     }
19 
20     @Override
21     public String toString() {
22         return "Dog{" + "name='" + name + '\'' + ", sex='" + sex + '\'' + ", age=" + age + ", fur='" + fur + '\''
23                 + ", breed='" + breed + '\'' + ", weight=" + weight + ", height=" + height + '}';
24     }
25 
26     public static class Builder {
27         private final String name; // 名称
28         private String sex; // 性别
29         private int age; // 年龄
30         private String fur; // 毛发
31         private String breed; // 品种
32         private float weight; // 体重
33         private float height; // 身高
34 
35         public Builder(String name) {
36             this.name = name;
37         }
38 
39         public Builder sex(String sex) {
40             this.sex = sex;
41             return this;
42         }
43 
44         public Builder age(int age) {
45             this.age = age;
46             return this;
47         }
48 
49         public Builder fur(String fur) {
50             this.fur = fur;
51             return this;
52         }
53 
54         public Builder breed(String breed) {
55             this.breed = breed;
56             return this;
57         }
58 
59         public Builder weight(float weight) {
60             this.weight = weight;
61             return this;
62         }
63 
64         public Builder height(float height) {
65             this.height = height;
66             return this;
67         }
68 
69         public Dog build() {
70             return new Dog(this);
71         }
72     }
73 }

 

 
Client端代码
public class Client {
    public static void main(String args[]) {
        Dog dog = new Dog.Builder("花花").age(1).height(50.0f).weight(50.0f).sex("boy").breed("拉布拉多").fur("yellow")
                .build();
        System.out.println(dog.toString());
    }
}

 

 
参考:

posted on 2018-06-04 09:10  下士闻道  阅读(206)  评论(0编辑  收藏  举报

导航