gpt4 book ai didi

c# - 具有嵌套对象的构建器模式

转载 作者:可可西里 更新时间:2023-11-01 09:05:04 24 4
gpt4 key购买 nike

嗨,我遇到了一个问题。

我想实现构建器模式,以便更轻松地创建我的对象。我面临的问题与嵌套对象有关。我想创建的对象中包含其他对象的列表,但我真的不知道如何处理它。

我希望能够执行以下操作(例如更简单的对象):

Receipt RestaurantReceipt = new ReceiptBuilder()
.withDate("value")
.withName("value")
.AddItem("value")
.WithIngredients("value")
.WithType("value")
.AddItem("value")
.WithIngredients("value")
.WithType("value")
.build();

或者类似的东西:

Receipt RestaurantReceipt = new ReceiptBuilder()
.withDate("value")
.withName("value")
.AddItem("value", item => {
.WithIngredients("value")
.WithType("value")
})
.AddItem("value", item => {
.WithIngredients("value")
.WithType("value")
})
.build();

示例应该代表我的情况,尽管如果有不止一种类型的嵌套对象。

最佳答案

给定这样的代码

var rb = new ReceiptBuilder();
var receipt = rb.WithName("Name")
.WithDate(DateTime.Now)
.WithItem("Item1", i => i.WithIngredients("Ingredients1"))
.WithItem("Item2", i => i.WithIngredients("Ingredients1"))
.Build();
Console.WriteLine(receipt);

您的构建器非常简单,利用 WithItem 构建器方法中的一些简单谓词,允许消费者以类似于顶级 ReceiptBuilder 的“构建器”模式配置每个项目:

public class ReceiptBuilder
{
private Receipt r;

public ReceiptBuilder()
{
r = new Receipt();
}

public ReceiptBuilder WithName(string name)
{
r.Name = name;
return this;
}

public ReceiptBuilder WithDate(DateTime dt)
{
r.Date = dt;
return this;
}

public ReceiptBuilder WithItem(string text, Action<ReceiptItemBuilder> itemBuilder)
{
var rib = new ReceiptItemBuilder(text);
itemBuilder(rib);
r.AddItem(rib.Build());
return this;
}

public Receipt Build()
{
return r;
}
}

public class ReceiptItemBuilder
{
private ReceiptItem ri;

public ReceiptItemBuilder(string text)
{
ri = new ReceiptItem(text);
}

public ReceiptItemBuilder WithIngredients(string ings)
{
ri.Ingredients = ings;
return this;
}

// WithType omitted for brevity.

internal ReceiptItem Build()
{
return ri;
}
}

工作示例:http://rextester.com/IRR50897

关于c# - 具有嵌套对象的构建器模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38480410/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com