Skip to content

建造者(Builder)模式 创建型模式

更新: 2023-05-24 11:11:27   字数: 0 字   时长: 0 分钟

将一个复杂对象分解成多个相对简单的部分,然后根据不同需要分别创建它们,最后构建成该复杂对象。

c#
// 建造者模式示例
using System;

// 产品类
class Product
{
    private string partA;
    private string partB;
    private string partC;

    public void SetPartA(string partA)
    {
        this.partA = partA;
    }

    public void SetPartB(string partB)
    {
        this.partB = partB;
    }

    public void SetPartC(string partC)
    {
        this.partC = partC;
    }

    public void Show()
    {
        Console.WriteLine("PartA: " + partA);
        Console.WriteLine("PartB: " + partB);
        Console.WriteLine("PartC: " + partC);
    }
}

// 抽象建造者类
abstract class Builder
{
    public abstract void BuildPartA();
    public abstract void BuildPartB();
    public abstract void BuildPartC();
    public abstract Product GetResult();
}

// 具体建造者类
class ConcreteBuilder1 : Builder
{
    private Product product = new Product();

    public override void BuildPartA()
    {
        product.SetPartA("PartA1");
    }

    public override void BuildPartB()
    {
        product.SetPartB("PartB1");
    }

    public override void BuildPartC()
    {
        product.SetPartC("PartC1");
    }

    public override Product GetResult()
    {
        return product;
    }
}

class ConcreteBuilder2 : Builder
{
    private Product product = new Product();

    public override void BuildPartA()
    {
        product.SetPartA("PartA2");
    }

    public override void BuildPartB()
    {
        product.SetPartB("PartB2");
    }

    public override void BuildPartC()
    {
        product.SetPartC("PartC2");
    }

    public override Product GetResult()
    {
        return product;
    }
}

// 指挥者类
class Director
{
    public void Construct(Builder builder)
    {
        builder.BuildPartA();
        builder.BuildPartB();
        builder.BuildPartC();
    }
}

// 客户端类
class Client
{
    static void Main(string[] args)
    {
        Director director = new Director();
        Builder builder1 = new ConcreteBuilder1();
        Builder builder2 = new ConcreteBuilder2();

        director.Construct(builder1);
        Product product1 = builder1.GetResult();
        product1.Show();

        director.Construct(builder2);
        Product product2 = builder2.GetResult();
        product2.Show();

        Console.ReadKey();
    }
}
你觉得这篇文章怎么样?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
评论
  • 按正序
  • 按倒序
  • 按热度