【发布时间】:2019-11-24 19:25:00
【问题描述】:
我试图通过在下面创建人员构建器对象来理解流利的构建器模式。我已经编写了我想使用的代码,但是在实现它时遇到了问题。我的问题如下:
- 调用
HavingJob()时,这应该会创建一个新作业,然后可以仅使用适用于作业的方法对其进行配置,并最终将其添加到人员的Jobs集合中。感觉应该返回它,以便可以在其上调用其他流畅的作业方法。暂时不知道如何实现,允许在该级别及更高级别进行链接。 - 在实现
IJobBuilder方法时,我无法访问他们在HavingJob()方法中创建的特定作业,因为我需要返回IJobBuilder以将流利的方法限制为仅与以下相关的方法工作。HavingJob()的诀窍是什么,以便那些特定的作业方法可以在特定作业上运行,同时仍然允许链接? - 一旦我走上了以
IJobBuilder结尾的流畅路径,我就不能再调用Build()或HavingJob()来添加其他作业。这个问题的答案是拥有一个继承自PersonBuilder的IJobBuilder的单独实现吗?
public class Person
{
public string Name { get; set; }
public List<Job> Jobs { get; set; }
public List<Phone> Phones { get; set; }
}
public class Phone
{
public string Number { get; set; }
public string Usage { get; set; }
}
public class Job
{
public string CompanyName { get; set; }
public int Salary { get; set; }
}
class Program
{
static void Main(string[] args)
{
var p = PersonBuilder
.Create()
.WithName("My Name")
.HavingPhone("222-222-2222")
.WithUsage("CELL")
.HavingJob()
.WithCompanyName("First Company")
.WithSalary(100)
.HavingJob()
.WithCompanyName("Second Company")
.WithSalary(200)
.Build();
Console.WriteLine(JsonConvert.SerializeObject(p));
}
}
public class PersonBuilder : IJobBuilder
{
protected Person Person;
public PersonBuilder() { Person = new Person(); }
public static PersonBuilder Create() => new PersonBuilder();
public PersonBuilder WithName(string name)
{
Person.Name = name;
return this;
}
public PersonBuilder HavingPhone(string phoneNumber)
{
// Need instance of phone
return this;
}
public PersonBuilder WithUsage(string phoneUsage)
{
// Need instance of phone
return this;
}
public IJobBuilder HavingJob()
{
// Need to create a job here and return it so that IJobBuilder methods work on specific instance right?
return this;
}
public Person Build() => Person;
public IJobBuilder WithCompanyName(string companyName)
{
// How do I set the company name if I don't have the job instance here
job.CompanyName = companyName;
return this;
}
public IJobBuilder WithSalary(int amount)
{
// How do I set the salary if I don't have a specific job instance here
job.Salary = amount;
return this;
}
}
public interface IJobBuilder
{
IJobBuilder WithCompanyName(string companyName);
IJobBuilder WithSalary(int salary);
}
【问题讨论】: