65.9K
CodeProject 正在变化。 阅读更多。
Home

学习 C# 中的建造者模式

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.67/5 (9投票s)

2016年2月29日

CPOL

3分钟阅读

viewsIcon

15233

downloadIcon

143

使用简单的电视建造者在 C# 中解释建造者模式

引言

设计模式非常有用,可以帮助解决许多实时问题。在本文中,我们将尝试通过一个 C# 示例程序来理解建造者模式。

背景

建造者模式属于创建型模式,因为它处理的是对象创建。这种模式在 .NET Framework 中被多次使用。一个例子是 ConnectionStringBuilder。当我们需要使用一系列复杂的流程来创建一个产品,而每个流程都可以分离时,建造者模式就派上了用场。这意味着我们可以分离对象创建的每个步骤,并且可以使用相同的对象机制来创建类似的产品或对象。

GoF 将建造者模式描述为将复杂对象的构建与其表示分离,以便相同的构建过程可以创建不同的表示。建造者模式包含以下项目

  • Director: Director 负责使用 Builder 接口或基类创建对象。
  • Builder: 基类或接口,其中提到了创建 Product 的不同步骤。
  • ConcreteBuilder: 定义了具体的建造者,它是上述 Builder 的实现。具体的 Builder 将帮助我们使用 Builder 中提到的一系列步骤来创建和获取下面的 Product
  • Product: 最终的 Product,它将通过许多复杂的步骤来创建。

Builder Pattern Sample using C#

Using the Code

为了开始示例程序,我创建了一个 Television (Product) 类,如下所示。这个 Product 将由 Builder 构建。我添加了不同的属性来显示产品的不同部分。

/// <summary>
/// Television - Product
/// </summary>
class Television
{
    public string Code { get; set; }
    public string DisplayTechnology { get; set; }
    public string HDFormat { get; set; }
    public string ScreenType { get; set; }
    public string Size { get; set; }
    public string Feature { get; set; }
}

现在,我们将创建 TelevisionBuilder (Builder),它将定义创建 Product 的复杂步骤。我们可以将 Builder 创建为接口或基类。如果您查看下面的类定义,您可以看到创建 Product 的步骤以及访问已创建 Product 的属性或方法。

/// <summary>
/// TelevisionBuilder - Builder
/// </summary>
abstract class TelevisionBuilder
{
    protected Television television;

    public abstract void SetCode();              // ProductCode
    public abstract void SetDisplayTechnology(); // LCD, LED, OLED, Plasma, CRT
    public abstract void SetHDFormat();   // Full HD, HD Ready, Ultra HD, None
    public abstract void SetScreenType(); // Curved, Flat, Standard
    public abstract void SetSize();       // 22, 32, 40, 42, 54
    public abstract void SetFeature();    // 3D, Smart, Standard , HDMI Ports, 
                                          // USB Ports, Built in WIFI, Ethernet, Remote

    //GetProduct
    public Television Television
    {
        get { return television; }
    }
}

定义 FullHD40TVBuilder (ConcreteBuilder1) 及其相应的实现。

/// <summary>
/// FullHD40TVBuilder - ConcreteBuilder1
/// </summary>
class FullHD40TVBuilder : TelevisionBuilder
{
    public FullHD40TVBuilder()
    {
        television = new Television();
    }

    public override void SetCode()
    {
        television.Code = "FullHD40TV";
    }

    public override void SetDisplayTechnology()
    {
        television.DisplayTechnology = "LCD";
    }

    public override void SetHDFormat()
    {
        television.HDFormat = "FullHD";
    }

    public override void SetScreenType()
    {
        television.ScreenType="Flat";
    }

    public override void SetSize()
    {
        television.Size="40";
    }

    public override void SetFeature()
    {
        television.Feature = "1 HDMI Ports, 1 USB Ports, Remote";
    }
}

定义 SMARTLED54TVBuilder (ConcreteBuilder2) 及其相应的实现。

/// <summary>
/// SMARTLED54TVBuilder - ConcreteBuilder2
/// </summary>
class SMARTLED54TVBuilder : TelevisionBuilder
{
    public SMARTLED54TVBuilder()
    {
        television = new Television();
    }

    public override void SetCode()
    {
        television.Code = "SMARTLED54TV";
    }

    public override void SetDisplayTechnology()
    {
        television.DisplayTechnology = "LED";
    }

    public override void SetHDFormat()
    {
        television.HDFormat =   "FullHD";
    }

    public override void SetScreenType()
    {
        television.ScreenType="Flat";
    }

    public override void SetSize()
    {
        television.Size="54";
    }

    public override void SetFeature()
    {
        television.Feature="2 HDMI Ports, 2 USB Ports, Built in WIFI, Ethernet, Remote";
    }
}

定义 Curved4K65LEDTVBuilder (ConcreteBuilder3) 及其相应的实现。

/// <summary>
/// Curved4K65LEDTVBuilder - ConcreteBuilder3
/// </summary>
class Curved4K65LEDTVBuilder : TelevisionBuilder
{
    public Curved4K65LEDTVBuilder()
    {
        television = new Television();
    }

    public override void SetCode()
    {
        television.Code = "Curved4K65LEDTV";
    }

    public override void SetDisplayTechnology()
    {
        television.DisplayTechnology = "LED";
    }

    public override void SetHDFormat()
    {
        television.HDFormat =   "4K Ultra HD";
    }

    public override void SetScreenType()
    {
        television.ScreenType="Curved";
    }

    public override void SetSize()
    {
        television.Size="65";
    }

    public override void SetFeature()
    {
        television.Feature="3 HDMI Ports, 2 USB Ports, 
                            Built in WIFI, Ethernet, Smart Remote";
    }
}

定义 LCD22TVBuilder (ConcreteBuilder4) 及其相应的实现。

/// <summary>
/// LCD22TVBuilder - ConcreteBuilder4
/// </summary>
class LCD22TVBuilder : TelevisionBuilder
{
    public LCD22TVBuilder()
    {
        television = new Television();
    }

    public override void SetCode()
    {
        television.Code = "LCD22TV";
    }

    public override void SetDisplayTechnology()
    {
        television.DisplayTechnology = "LCD";
    }

    public override void SetHDFormat()
    {
        television.HDFormat = "None";
    }

    public override void SetScreenType()
    {
        television.ScreenType = "Flat";
    }

    public override void SetSize()
    {
        television.Size = "22";
    }

    public override void SetFeature()
    {
        television.Feature = "Remote";
    }
}

到目前为止,我们已经定义了 ProductBuilderConcreteBuilder。现在让我们创建 TelevisionManufacturer 作为 Director,这里的参数是 Builder,并且 Director 负责根据需求调用这些步骤。

/// <summary>
/// TelevisionManufacturer - Director
/// </summary>
class TelevisionManufacturer
{
    //Constructing Product
    public void Construct(TelevisionBuilder televisionBuilder)
    {
        //Series of Complex Process
        televisionBuilder.SetCode();
        televisionBuilder.SetDisplayTechnology();
        televisionBuilder.SetHDFormat();
        televisionBuilder.SetScreenType();
        televisionBuilder.SetSize();
        televisionBuilder.SetFeature();
    }
}

我创建了一个控制台 Program 来测试建造者模式示例,这里的最终客户端根本不用担心复杂的对象创建。

/// <summary>
/// Program class which demonstrates the builder usage
/// </summary>
class Program
{
    /// <summary>
    /// Main method of Program.cs
    /// </summary>
    /// <param name="args"></param>
    static void Main(string[] args)
    {
        TelevisionBuilder builder;

        TelevisionManufacturer director = new TelevisionManufacturer();

        builder = new FullHD40TVBuilder();
        director.Construct(builder);
        Television product1 = builder.Television;

        Console.WriteLine("Code:{0}", product1.Code);

        builder = new SMARTLED54TVBuilder();
        director.Construct(builder);
        Television product2 = builder.Television;

        Console.WriteLine("Code:{0}", product2.Code);

        builder = new Curved4K65LEDTVBuilder();
        director.Construct(builder);
        Television product3 = builder.Television;

        Console.WriteLine("Code:{0}", product3.Code);

        builder = new LCD22TVBuilder();
        director.Construct(builder);
        Television product4 = builder.Television;

        Console.WriteLine("Code:{0}", product4.Code);
        //Wait for UserInteraction
        Console.ReadKey();
    }
}

输出

为了使代码看起来简单,已从上面的 Console.Writeline 中删除了一些代码。您可以参考附加项目中的 *Program.cs* 文件以查看最终版本。

Buider Pattern Sample Output

要自己探索此示例,您可以下载附加的代码或创建一个名为“BuilderPatternSample”的控制台项目,并将 *Program.cs* 的内容替换为以下代码块。

Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BuilderPatternSample
{
    /// <summary>
    /// Program class which demonstrates the builder usage
    /// </summary>
    class Program
    {
        /// <summary>
        /// Main method of Program.cs
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            TelevisionBuilder builder;

            TelevisionManufacturer director = new TelevisionManufacturer();

            builder = new FullHD40TVBuilder();
            director.Construct(builder);
            Television product1 = builder.Television;

            Console.WriteLine("     ┌───────────────────────────────────Code:{0}───────────────────────────────┐",
                              product1.Code);
            Console.WriteLine("     │                         DisplayTechnology:{0}                                   │",
                              product1.DisplayTechnology);
            Console.WriteLine("     │                         HDFormat:{0}                                         │",
                              product1.HDFormat);
            Console.WriteLine("     │                         ScreenType:{0}                                         │",
                              product1.ScreenType);
            Console.WriteLine("     │                         Size:{0}                                                 │",
                              product1.Size);
            Console.WriteLine("     │                         Feature:{0}               │", product1.Feature);
            Console.WriteLine("     └─────────────────────────────────────────────────────────────────────────────────┘");

            builder = new SMARTLED54TVBuilder();
            director.Construct(builder);
            Television product2 = builder.Television;

            Console.WriteLine("     ┌──────────────────────────────────Code:{0}──────────────────────────────┐",
                              product2.Code);
            Console.WriteLine("     │        DisplayTechnology:{0}                                                    │",
                              product2.DisplayTechnology);
            Console.WriteLine("     │        HDFormat:{0}                                                          │",
                              product2.HDFormat);
            Console.WriteLine("     │        ScreenType:{0}                                                          │",
                              product2.ScreenType);
            Console.WriteLine("     │        Size:{0}                                                                  │",
                              product2.Size);
            Console.WriteLine("     │        Feature:{0}       │", product2.Feature);
            Console.WriteLine("     └─────────────────────────────────────────────────────────────────────────────────┘");

            builder = new Curved4K65LEDTVBuilder();
            director.Construct(builder);
            Television product3 = builder.Television;

            Console.WriteLine("     ┌─────────────────────────────────Code:{0}────────────────────────────┐",
                              product3.Code);
            Console.WriteLine("     │       DisplayTechnology:{0}                                                     │",
                              product3.DisplayTechnology);
            Console.WriteLine("     │       HDFormat:{0}                                                      │",
                              product3.HDFormat);
            Console.WriteLine("     │       ScreenType:{0}                                                         │",
                              product3.ScreenType);
            Console.WriteLine("     │       Size:{0}                                                                   │",
                              product3.Size);
            Console.WriteLine("     │       Feature:{0}  │", product3.Feature);
            Console.WriteLine("     └─────────────────────────────────────────────────────────────────────────────────┘");

            builder = new LCD22TVBuilder();
            director.Construct(builder);
            Television product4 = builder.Television;

            Console.WriteLine("     ┌────────────────────────────────────Code:{0}─────────────────────────────────┐",
                              product4.Code);
            Console.WriteLine("     │                         DisplayTechnology:{0}                                   │",
                              product4.DisplayTechnology);
            Console.WriteLine("     │                         HDFormat:{0}                                           │",
                              product4.HDFormat);
            Console.WriteLine("     │                         ScreenType:{0}                                         │",
                              product4.ScreenType);
            Console.WriteLine("     │                         Size:{0}                                                 │",
                              product4.Size);
            Console.WriteLine("     │                         Feature:{0}                                          │",
                              product4.Feature);
            Console.WriteLine("     └─────────────────────────────────────────────────────────────────────────────────┘");

            //Wait for UserInteraction
            Console.ReadKey();
        }
    }

    /// <summary>
    /// Television - Product
    /// </summary>
    class Television
    {
        public string Code { get; set; }
        public string DisplayTechnology { get; set; }
        public string HDFormat { get; set; }
        public string ScreenType { get; set; }
        public string Size { get; set; }
        public string Feature { get; set; }
    }

    /// <summary>
    /// TelevisionBuilder - Builder
    /// </summary>
    abstract class TelevisionBuilder
    {
        protected Television television;

        public abstract void SetCode();              // ProductCode
        public abstract void SetDisplayTechnology(); // LCD, LED, OLED, Plasma, CRT
        public abstract void SetHDFormat();   // Full HD, HD Ready, Ultra HD, None
        public abstract void SetScreenType(); // Curved, Flat, Standard
        public abstract void SetSize();       // 22, 32, 40, 42, 54
        public abstract void SetFeature();    // 3D, Smart, Standard , HDMI Ports, 
                                              // USB Ports, Built in WIFI, Ethernet, Remote

        //GetProduct
        public Television Television
        {
            get { return television; }
        }
    }

    /// <summary>
    /// FullHD40TVBuilder - ConcreteBuilder1
    /// </summary>
    class FullHD40TVBuilder : TelevisionBuilder
    {
        public FullHD40TVBuilder()
        {
            television = new Television();
        }

        public override void SetCode()
        {
            television.Code = "FullHD40TV";
        }

        public override void SetDisplayTechnology()
        {
            television.DisplayTechnology = "LCD";
        }

        public override void SetHDFormat()
        {
            television.HDFormat = "FullHD";
        }

        public override void SetScreenType()
        {
            television.ScreenType = "Flat";
        }

        public override void SetSize()
        {
            television.Size = "40";
        }

        public override void SetFeature()
        {
            television.Feature = "1 HDMI Ports, 1 USB Ports, Remote";
        }
    }

    /// <summary>
    /// SMARTLED54TVBuilder - ConcreteBuilder2
    /// </summary>
    class SMARTLED54TVBuilder : TelevisionBuilder
    {
        public SMARTLED54TVBuilder()
        {
            television = new Television();
        }

        public override void SetCode()
        {
            television.Code = "SMARTLED54TV";
        }

        public override void SetDisplayTechnology()
        {
            television.DisplayTechnology = "LED";
        }

        public override void SetHDFormat()
        {
            television.HDFormat = "FullHD";
        }

        public override void SetScreenType()
        {
            television.ScreenType = "Flat";
        }

        public override void SetSize()
        {
            television.Size = "54";
        }

        public override void SetFeature()
        {
            television.Feature = "2 HDMI Ports, 
                                  2 USB Ports, Built in WIFI, Ethernet, Remote";
        }
    }

    /// <summary>
    /// Curved4K65LEDTVBuilder - ConcreteBuilder3
    /// </summary>
    class Curved4K65LEDTVBuilder : TelevisionBuilder
    {
        public Curved4K65LEDTVBuilder()
        {
            television = new Television();
        }

        public override void SetCode()
        {
            television.Code = "Curved4K65LEDTV";
        }

        public override void SetDisplayTechnology()
        {
            television.DisplayTechnology = "LED";
        }

        public override void SetHDFormat()
        {
            television.HDFormat = "4K Ultra HD";
        }

        public override void SetScreenType()
        {
            television.ScreenType = "Curved";
        }

        public override void SetSize()
        {
            television.Size = "65";
        }

        public override void SetFeature()
        {
            television.Feature = "3 HDMI Ports, 2 USB Ports, Built in WIFI, 
                                  Ethernet, Smart Remote";
        }
    }

    /// <summary>
    /// LCD22TVBuilder - ConcreteBuilder4
    /// </summary>
    class LCD22TVBuilder : TelevisionBuilder
    {
        public LCD22TVBuilder()
        {
            television = new Television();
        }

        public override void SetCode()
        {
            television.Code = "LCD22TV";
        }

        public override void SetDisplayTechnology()
        {
            television.DisplayTechnology = "LCD";
        }

        public override void SetHDFormat()
        {
            television.HDFormat = "None";
        }

        public override void SetScreenType()
        {
            television.ScreenType = "Flat";
        }

        public override void SetSize()
        {
            television.Size = "22";
        }

        public override void SetFeature()
        {
            television.Feature = "Remote";
        }
    }

    /// <summary>
    /// TelevisionManufacturer - Director
    /// </summary>
    class TelevisionManufacturer
    {
        //Constructing Product
        public void Construct(TelevisionBuilder televisionBuilder)
        {
            //Series of Complex Process
            televisionBuilder.SetCode();
            televisionBuilder.SetDisplayTechnology();
            televisionBuilder.SetHDFormat();
            televisionBuilder.SetScreenType();
            televisionBuilder.SetSize();
            televisionBuilder.SetFeature();
        }
    }
}

摘要

在本文中,我用一个简单的 C# 应用程序解释了建造者模式。我希望您喜欢这篇文章,并且您的知识得到了一些增值。请不要忘记标记您的投票、建议和反馈,以提高本文和即将发布的文章的质量。

历史

  • 2016 年 2 月 29 日:初始版本
© . All rights reserved.