Skip to content

Commit dfdea96

Browse files
committed
增加Builder设计模式
1 parent 4d5f713 commit dfdea96

2 files changed

Lines changed: 89 additions & 0 deletions

File tree

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
package cn.byhieg.designpatterntutorial.builder;
2+
3+
/**
4+
* Created by shiqifeng on 2017/5/7.
5+
6+
*/
7+
public class Person {
8+
9+
private int age;
10+
private String name;
11+
private int height;
12+
private int weight;
13+
14+
public int getAge() {
15+
return age;
16+
}
17+
18+
public String getName() {
19+
return name;
20+
}
21+
22+
public int getHeight() {
23+
return height;
24+
}
25+
26+
public int getWeight() {
27+
return weight;
28+
}
29+
30+
public Person(Builder builder) {
31+
age = builder.age;
32+
name = builder.name;
33+
height = builder.height;
34+
weight = builder.weight;
35+
}
36+
37+
@Override
38+
public String toString() {
39+
return "age = " + age + " name = " + name + " height = " + height + " weight = " + weight;
40+
}
41+
42+
public static class Builder{
43+
44+
private int age;
45+
private String name;
46+
private int height;
47+
private int weight;
48+
49+
public Builder setAge(int age) {
50+
this.age = age;
51+
return this;
52+
}
53+
54+
public Builder setName(String name) {
55+
this.name = name;
56+
return this;
57+
}
58+
59+
public Builder setHeight(int height) {
60+
this.height = height;
61+
return this;
62+
}
63+
64+
public Builder setWeight(int weight) {
65+
this.weight = weight;
66+
return this;
67+
}
68+
69+
public Person build() {
70+
return new Person(this);
71+
}
72+
}
73+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package cn.byhieg.designpatterntutorialtest;
2+
3+
import cn.byhieg.designpatterntutorial.builder.Person;
4+
import junit.framework.TestCase;
5+
6+
/**
7+
* Created by shiqifeng on 2017/5/7.
8+
9+
*/
10+
public class BuilderTest extends TestCase {
11+
public void testBuild() throws Exception {
12+
Person person = new Person.Builder().setAge(24).setHeight(178).setName("byhieg").setWeight(80).build();
13+
System.out.println(person.toString());
14+
}
15+
16+
}

0 commit comments

Comments
 (0)