建造者模式

将一个复杂对象的构建和它的表示分离,使得同样的构建过程可以创建不同的表示.
用户只需指定需要构建的类型,过程和细节不需知道.

1
2
3
4
5
6
7
8
9
10
11
package builder;

/**
* Created by hero on 17-2-18.
*/
public interface Builder {
/** 不可缺少的步骤 */
void hands();
void legs();
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package builder;

/**
* Created by hero on 17-2-18.
*/
public class FatBuilder implements Builder{
public void hands() {
System.out.println("胖手");
}

public void legs() {
System.out.println("胖腿");
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package builder;

/**
* Created by hero on 17-2-18.
*/
public class ThinBuilder implements Builder {
public void hands() {
System.out.println("瘦手");
}

public void legs() {
System.out.println("瘦腿");
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package builder;

/**
* Created by hero on 17-2-18.
*/
public class Director {
private Builder builder;

public Director(Builder builder) {
this.builder = builder;
}

/** 封装具体过程 */
public void build() {
builder.hands();
builder.legs();
}

public void setBuilder(Builder builder) {
this.builder = builder;
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package builder;

/**
* Created by hero on 17-2-18.
*/
public class Main {
public static void main(String[] args) {
Director director = new Director(new FatBuilder());
director.build();

director.setBuilder(new ThinBuilder());
director.build();
}
}