건설자 모델과 공장 모델의 차이

6799 단어
그것들의 목적은 모두 하나의 대상을 만드는 것이다
공장 모델은 전체 대상의 창설 방법을 중시하고 건설자 모델은 대상의 창설 과정을 중시하며 창설 대상의 과정 방법은 창설할 때 자유롭게 호출할 수 있다.
 
건설자 모델의 예를 보면 알 수 있다.
 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));
}

좋은 웹페이지 즐겨찾기