它们目的都是创建一个对象
工厂模式注重的是整体对象的创建方法,而建造者模式注重的是对象的创建过程,创建对象的过程方法可以在创建时自由调用。
看一下建造者模式的例子就明白了:
1 public class EmployeeBuilder
2 {
3 private int id = 1;
4 private string firstname = "first";
5 private string lastname = "last";
6 private DateTime birthdate = DateTime.Today;
7 private string street = "street";
8
9 public Employee Build()
10 {
11 return new Employee(id, firstname, lastname, birthdate, street);
12 }
13
14 public EmployeeBuilder WithFirstName(string firstname)
15 {
16 this.firstname = firstname;
17 return this;
18 }
19
20 public EmployeeBuilder WithLastName(string lastname)
21 {
22 this.lastname = lastname;
23 return this;
24 }
25
26 public EmployeeBuilder WithBirthDate(DateTime birthdate)
27 {
28 this.birthdate = birthdate;
29 return this;
30 }
31
32 public EmployeeBuilder WithStreet(string street)
33 {
34 this.street = street;
35 return this;
36 }
37
38 public static implicit operator Employee(EmployeeBuilder instance)
39 {
40 return instance.Build();
41 }
42 }
调用:
void main(){
Employee emp1 = new EmployeeBuilder().WithFirstName("Kenneth")
.WithLastName("Truyers");
Employee emp2 = new EmployeeBuilder().WithBirthDate(new DateTime(1983, 1,1));
}