以下是实现链式调用和组合的完整代码示例,用于展示如何使用Builder
设计模式来创建和验证对象,并实现流畅的API调用:
using System;
public class Person
{
public string Name { get; private set; }
public int Age { get; private set; }
public string Address { get; private set; }
public string Job { get; private set; }
private Person(Builder builder)
{
Name = builder.Name;
Age = builder.Age;
Address = builder.Address;
Job = builder.Job;
}
public class Builder
{
public string Name { get; private set; }
public int Age { get; private set; }
public string Address { get; private set; }
public string Job { get; private set; }
// 构造函数强制要求必选参数
public Builder(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
throw new ArgumentException("Name is required");
}
Name = name;
}
public Builder SetAge(int age)
{
if (age < 0)
{
throw new ArgumentException("Age cannot be negative");
}
Age = age;
return this;
}
public Builder SetAddress(string address)
{
if (string.IsNullOrWhiteSpace(address))
{
throw new ArgumentException("Address cannot be empty");
}
Address = address;
return this;
}
public Builder SetJob(string job)
{
Job = job;
return this;
}
public Person Build()
{
// 其他验证逻辑可以放在这里
return new Person(this);
}
}
}
public class Program
{
public static void Main(string[] args)
{
try
{
var person = new Person.Builder("John Doe")
.SetAge(30)
.SetAddress("123 Main St")
.SetJob("Software Engineer")
.Build();
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}, Address: {person.Address}, Job: {person.Job}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
说明
- 必选参数:在
Builder
的构造函数中强制传递,如Name
。 - 链式调用:每个设置器方法返回
this
,从而支持链式调用。 - 验证逻辑:在设置器方法和
Build
方法中进行参数验证,确保数据有效。
输出示例
如果运行上述代码,输出将会是:
Name: John Doe, Age: 30, Address: 123 Main St, Job: Software Engineer
此实现展示了如何通过Builder模式进行链式方法调用和对象组合,从而创建灵活且可扩展的对象实例。