首页 > 其他 > 详细

设计模式之Builder建造者模式 代码初见

时间:2019-03-09 17:41:35      阅读:184      评论:0      收藏:0      [点我收藏+]
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建造者模式 代码初见

原文:https://www.cnblogs.com/vigorz/p/10501961.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!