背景
- 结合泛型和递归,也能实现流畅方法,但比较烧脑
- 实现
- Gx<T>继承Gy<T>或抽象类A(即递归),引入Gy<T>或A的内容
- Gn(=Gx|Gy)输入类型和方法输出类型均为T(=EmployeeDirector),保持一致
- Gn的方法输出类型是其子类,符合返回容器的原则
- EmployeeDirector中的方法返回自身,符合返回容器的原则
- 可通过EmployeeDirector类理解以上含义
示例
using static System.Console;
namespace FluentRecursiveGeneric
{
public class Employee
{
public string Name { get; set; }
public string Position { get; set; }
public double Salary { get; set; }
public override string ToString()
=> $"Name: {Name}, Position: {Position}, Salary: {Salary}";
}
public abstract class EmployeeBuilder
{
protected Employee employee = new Employee();
public EmployeeBuilder() { }
public Employee Build() => employee;
}
public class EmployeeNameBuilder<T> : EmployeeBuilder
where T : EmployeeNameBuilder<T>
{
public T SetName(string name)
{
employee.Name = name;
return (T)this; // T为当前类的子类,才能转换
}
}
public class EmployeePositionBuilder<T> : EmployeeNameBuilder<T>
where T : EmployeePositionBuilder<T>
{
public T SetPosition(string position)
{
employee.Position = position;
return (T)this;
}
}
public class EmployeeSalaryBuilder<T> : EmployeePositionBuilder<T>
where T : EmployeeSalaryBuilder<T>
{
public T At(double salary)
{
employee.Salary = salary;
return (T)this;
}
}
// 继承薪资类取得At()方法
// 嵌套类中均返回类型T = EmployeeDirector
public class EmployeeDirector : EmployeeSalaryBuilder<EmployeeDirector>
{
// 返回容器类
public static EmployeeDirector NewEmployee => new EmployeeDirector();
}
class Program
{
static void Main(string[] args)
{
var employee = EmployeeDirector.NewEmployee
.SetName("Zhang")
.SetPosition("Manager")
.At(1000)
.Build();
WriteLine(employee);
ReadKey();
}
}
}
网友评论