設計模式之Builder建造者模式 代碼初見
阿新 • • 發佈:2019-03-09
() 分享 void this emp 技術 傳送門 birt pat
public class EmployeeBuilder { private int id = 1; private string firstname = "first"; private string lastname = "last"; private DateTime birthdate = DateTime.Today; private string street = "street"; public Employee Build() { return new Employee(id, firstname, lastname, birthdate, street); } public EmployeeBuilder WithFirstName(string firstname) { this.firstname = firstname; return this; } public EmployeeBuilder WithLastName(string lastname) { this.lastname = lastname; return this; } public EmployeeBuilder WithBirthDate(DateTime birthdate) { this.birthdate = birthdate; return this; } public EmployeeBuilder WithStreet(string street) { this.street = street; return this; } public static implicit operator Employee(EmployeeBuilder instance) { return instance.Build(); } }
測試
public class EmployeeTest { [Test] public void GetFullNameReturnsCombination() { // Arrange Employee emp = new EmployeeBuilder().WithFirstName("Kenneth") .WithLastName("Truyers"); // Act string fullname = emp.getFullName(); // Assert Assert.That(fullname, Is.EqualTo("Kenneth Truyers")); } [Test] public void GetAgeReturnsCorrectValue() { // Arrange Employee emp = new EmployeeBuilder().WithBirthDate(new DateTime(1983, 1,1)); // Act int age = emp.getAge(); // Assert Assert.That(age, Is.EqualTo(DateTime.Today.Year - 1983)); } }
參考
想要看到更多瑋哥的學習筆記、考試復習資料、面試準備資料?想要看到IBM工作時期的技術積累和國外初創公司的經驗總結?
敬請關註:
瑋哥的博客 —— CSDN的傳送門
瑋哥的博客 —— 簡書的傳送門
瑋哥的博客 —— 博客園的傳送門
設計模式之Builder建造者模式 代碼初見