( Design Patterns ) Creational D

2016-12-07  本文已影响0人  乔什华

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 Pattern UMLBuilder 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

上一篇下一篇

猜你喜欢

热点阅读