流式接口(fluent interface)

流式接口(fluent interface)是软件工程面向对象API的一种实现方式,以提供更为可读的源代码。最早由Eric EvansMartin Fowler于2005年提出。

通常采取方法瀑布调用 (具体说是方法链式调用)来转发一系列对象方法调用的上下文 [1]。这个上下文(context)通常是指:

  • 通过被调方法的返回值定义
  • 自引用,新的上下文等于老的上下文。
  •  只有一条规则:该方法必须返回非void值。

流式接口可用于一系列方法,他们运行在同一对象上。linq大量使用了流式接口

 

// Defines the data context
class Context
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Sex { get; set; }
    public string Address { get; set; }
}

class Customer
{
    private Context _context = new Context(); // Initializes the context

    // set the value for properties
    public Customer FirstName(string firstName)
    {
        _context.FirstName = firstName;
        return this;
    }

    public Customer LastName(string lastName)
    {
        _context.LastName = lastName;
        return this;
    }

    public Customer Sex(string sex)
    {
        _context.Sex = sex;
        return this;
    }

    public Customer Address(string address)
    {
        _context.Address = address;
        return this;
    }

    // Prints the data to console
    public void Print()
    {
        Console.WriteLine("First name: {0} \nLast name: {1} \nSex: {2} \nAddress: {3}", _context.FirstName, _context.LastName, _context.Sex, _context.Address);
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Object creation
        Customer c1 = new Customer();
        // Using the method chaining to assign & print data with a single line
        c1.FirstName("vinod").LastName("srivastav").Sex("male").Address("bangalore").Print();
    }
}

 

posted @ 2022-10-01 09:56  小林野夫  阅读(784)  评论(0编辑  收藏  举报
原文链接:https://www.cnblogs.com/cdaniu/