美文网首页
( Design Patterns ) Creational D

( Design Patterns ) Creational D

作者: 乔什华 | 来源:发表于2016-12-07 20:31 被阅读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: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 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

    相关文章

      网友评论

          本文标题:( Design Patterns ) Creational D

          本文链接:https://www.haomeiwen.com/subject/ovcjmttx.html