背景
示例
using static System.Console;
namespace FluentFacade
{
// 数据类
public class Car
{
public string Type { get; set; }
public string Color { get; set; }
public int NumberOfDoors { get; set; }
public string City { get; set; }
public string Address { get; set; }
public override string ToString()
=> $"Type: {Type}, Color: {Color}, NumberOfDoors: {NumberOfDoors}, City: {City}, Address: {Address}";
}
public class Facade
{
protected Car Car = new Car();
public Facade() { }
public Car Build() => Car;
public InfoBuilder Info => new InfoBuilder(Car);
public AddressBuilder Address => new AddressBuilder(Car);
}
// 继承门面类引入其内容,下同
public class InfoBuilder : Facade
{
public InfoBuilder(Car car)
{
Car = car;
}
// 返回容器类,下同
public InfoBuilder TypeIs(string type)
{
Car.Type = type;
return this;
}
public InfoBuilder ColorIs(string color)
{
Car.Color = color;
return this;
}
public InfoBuilder NumberOfDoorsIs(int number)
{
Car.NumberOfDoors = number;
return this;
}
}
public class AddressBuilder : Facade
{
public AddressBuilder(Car car)
{
Car = car;
}
public AddressBuilder CityIs(string city)
{
Car.City = city;
return this;
}
public AddressBuilder AddressIs(string address)
{
Car.Address = address;
return this;
}
}
class Program
{
static void Main(string[] args)
{
var car = new Facade()
.Info
.TypeIs("BWM")
.ColorIs("Red")
.NumberOfDoorsIs(5)
.Address
.CityIs("Shanghai")
.AddressIs("Yangpu Rd.JY 55")
.Build();
WriteLine(car);
ReadKey();
}
}
}
网友评论