( Design Patterns ) Creational Design Patterns 3 -- Builder Pattern

Definition

Separate the construction of a complex object from its representation so that the same construction process can create different representations, which allows for the step-by-step creation of complex objects using the correct sequence of action.

This pattern is used when a complex object that needs to be created is constructed by constituent parts that must be created in the same order or by using a specific algorithm.

Components

  • Builder:Interface for creating the actual products. Each step is an abstract method.
  • ConcreteBuilder:Implementation for builder.
  • Director:represent class that controls algorithm used for creation of complex object.
  • Product:complex object that is being built.
Builder Pattern UML
Builder Pattern UML

Code

public class DirectorCashier
{
    public void BuildFood(Builder builder)
    {
        builder.BuildPart1();
        builder.BuildPart2();
    }
}

public abstract class Builder
{
    public abstract void BuildPart1();

    public abstract void BuildPart2();

    public abstract Product GetProduct();
}

public class ConcreteBuilder1 : Builder
{
    protected Product _product;
    public ConcreteBuilder1()
    {
        _product = new Product();
    }
        
    public override void BuildPart1()
    {
        this._product.Add("Hamburger", "2");
    }
        
    public override void BuildPart2()
    {
        this._product.Add("Drink", "1");
    }

    public override Product GetProduct()
    {
        return this._product;
    }
}

public class Product
{
    public Dictionary<string, string> products = new Dictionary<string, string>();
        
    public void Add(string name, string value)
    {
        products.Add(name, value);
    }
        
    public void ShowToClient()
    {
        foreach (var p in products)
        {
            Console.WriteLine($"{p.Key} {p.Value}");
        }
    }
}

public class BuilderPatternRunner : IPattterRunner
{
    public void RunPattern()
    {
        var Builder1 = new ConcreteBuilder1();
        var Director = new DirectorCashier();

        Director.BuildFood(Builder1);
        Builder1.GetProduct().ShowToClient();
    }
}

Reference

Design Patterns 1 of 3 - Creational Design Patterns - CodeProject

Factory Patterns - Abstract Factory Pattern - CodeProject

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容