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

本文主要介绍了设计模式中的Builder建造者模式,通过实例代码展示其基本使用和应用场景。同时,提供了作者玮哥的学习资源,包括CSDN、简书和博客园的博客链接,分享他的技术积累和实战经验。
摘要由CSDN通过智能技术生成
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的传送门

玮哥的博客 —— 简书的传送门

玮哥的博客 —— 博客园的传送门

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值