建造者模式和工廠模式的區別


它們目的都是創建一個復雜的對象

工廠模式注重的是整體對象的創建方法,而建造者模式注重的是對象的創建過程,創建對象的過程方法可以在創建時自由調用。

 

看一下建造者模式的例子就明白了:

 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));
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM