設計模式之建造者模式和工廠模式 使用小結


Builder(In Test)建造者模式是什么

Normal Pattern

public class Employee
{
    public Employee(int id, string firstname, string lastname, DateTime birthdate, string street)
    {
        this.ID = id;
        this.FirstName = firstname;
        this.LastName = lastname;
        this.BirthDate = birthdate;
        this.Street = street;
    }

    public int ID { get; private set; }

    public string FirstName { get; private set; }

    public string LastName { get; private set; }

    public DateTime BirthDate { get; private set; }

    public string Street { get; private set; }

    public string getFullName()
    {
        return this.FirstName + " " + this.LastName;
    }

    public int getAge()
    {
        DateTime today = DateTime.Today;
        int age = today.Year - BirthDate.Year;
        if (BirthDate > today.AddYears(-age)) age--;
        return age;
    }
}

  • All values are passed in in the constructor
  • All properties are read-only (at least from outside of this class)
  • Methods provide access to calculated values (getFullName and getAge)

The Builder Pattern & The Factory Pattern

工廠方法模式注重的是整體對象的創建方法,而建造者模式注重的是部件構建的過程,旨在通過一步一步地精確構造創建出一個復雜的對象。

工廠模式關心整體,建造者模式關心細節。

我們舉個簡單例子來說明兩者的差異,如要制造一個超人,如果使用工廠方法模式,直接產生出來的就是一個力大無窮、能夠飛翔、內褲外穿的超人;

而如果使用建造者模式,則需要組裝手、頭、腳、軀干等部分,然后再把內褲外穿,於是一個超人就誕生了。參考

更加的Flexible and expressive

The Builder Pattern 建造者模式

應用案例:麥當勞套餐基本上都是以一個漢堡和一杯飲料組成套餐。

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

The resulting unit tests

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

工廠模式

定義一個創建對象的接口,讓其子類自己決定實例化哪一個工廠類,工廠模式使其創建過程延遲到子類進行。

在工廠模式中,我們在創建對象時不會對客戶端暴露創建邏輯,並且是通過使用一個共同的接口來指向新創建的對象。

應用案例:如果需要一個汽車,只需要去車場提車就好了,不用知道車子是怎么造的。

優點:

  1. 一個調用者想創建一個對象,只要知道其名稱就可以了。

  2. 擴展性高,如果想增加一個產品,只要擴展一個工廠類就可以。

  3. 屏蔽產品的具體實現,調用者只關心產品的接口。

public class ProductFactory {
    public static Product produce(String productName) throws Exception {
        switch (productName) {
            case "tv":
                return new Tv();
            case "car":
                return new Car();
            default:
                throw new Exception("沒有該產品");
        }
    }
}


測試方法:

try {
    ProductFactory.produce("car");
} catch (Exception e) {
    e.printStackTrace();
}

其他參考

參考

參考

參考


想要看到更多瑋哥的學習筆記、考試復習資料、面試准備資料?想要看到IBM工作時期的技術積累和國外初創公司的經驗總結?

敬請關注:

瑋哥的博客 —— CSDN的傳送門

瑋哥的博客 —— 簡書的傳送門

瑋哥的博客 —— 博客園的傳送門


免責聲明!

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



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