4、建造者模式

建造者模式也叫生成器模式,主要思想是让建造者关注产出,不关心过程

public class House
{
    public string Foundation { get; set; }
    public string Structure { get; set; }
    public string Roof { get; set; }
    public string Interior { get; set; }

    public override string ToString()
    {
        return $"Foundation: {Foundation}, Structure: {Structure}, Roof: {Roof}, Interior: {Interior}";
    }
}

public class Director
{
    private IHouseBuilder _houseBuilder;
    public Director(IHouseBuilder houseBuilder)
    {
        _houseBuilder = houseBuilder;
    }

    public void Builder()
    {
        _houseBuilder.BuildFoundation();
        _houseBuilder.BuildStructure();
        _houseBuilder.BuildRoof();
        _houseBuilder.BuildInterior();
    }
}

public interface IHouseBuilder
{
    void BuildFoundation();
    void BuildStructure();
    void BuildRoof();
    void BuildInterior();

    House GetHouse();
}

public class HouseBuilderA : IHouseBuilder
{
    private House _house = new House();

    public void BuildFoundation()
    {
        _house.Foundation = "HouseBuilderA foundation";
    }

    public void BuildInterior()
    {
        _house.Interior = "HouseBuilderA interior";
    }

    public void BuildRoof()
    {
        _house.Roof = "HouseBuilderA roof";
    }

    public void BuildStructure()
    {
        _house.Structure = "HouseBuilderA structure";
    }

    public House GetHouse()
    {
        return _house;
    }
}
public class HouseBuilderB : IHouseBuilder
{
    private House _house = new House();

    public void BuildFoundation()
    {
        _house.Foundation = "HouseBuilderB foundation";
    }

    public void BuildInterior()
    {
        _house.Interior = "HouseBuilderB interior";
    }

    public void BuildRoof()
    {
        _house.Roof = "HouseBuilderB roof";
    }

    public void BuildStructure()
    {
        _house.Structure = "HouseBuilderB structure";
    }

    public House GetHouse()
    {
        return _house;
    }
}

 

 

 
posted @ 2024-10-22 15:04  刘继先  阅读(4)  评论(0编辑  收藏  举报