应用FluenceInterface设计让使用者更方便

 

 

image

--《设计模式_基于C#的工程化实现及扩展》

相信有用过jquery的朋友,会清楚Jquery在使用上经常是$().fun1(…).fun2(…)这种样式的。Fluent Interface就是用来实现这种调用方式的。

 

一个简单的FluentInterface类设计

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace testFluentInterface
{
    class FluentInterfaceClass
    {
        public FluentInterfaceClass SaySome(string sth) {   //应用Fluence Interface设计
            Console.WriteLine(sth);
            return this;            //返回对象本身
        }
        public FluentInterfaceClass SaySome2(string sth)  //普通的设计方式
        {
            Console.WriteLine(sth);
        }
    }
}
复制代码

测试类

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace testFluentInterface
{
    class Program
    {
        static void Main(string[] args)
        {
            FluentInterfaceClass fic = new FluentInterfaceClass();
            fic.SaySome("1").SaySome("2").SaySome("3");//连贯的调用
            Console.WriteLine("===============================================================");
            fic.SaySome2("1");              //调用1次
            fic.SaySome2("2");              //调用2次
            fic.SaySome2("3");              //调用3次
        }
    }
}
复制代码

 

从测试类中,我们可以发现FluentInterfaceClass中方法调用方式也非常简单,一直点下去就行。而普通的设计中,我们则需要通过写多次实体来调用实体的方法。

运行结果截图

image

实现的原理

      相信大家都看清楚了吧?使用连贯接口(Fluence Interface)的设计其实就是在方法的最后返回类实体本身(this)。

posted @   陈哈哈  阅读(210)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· [AI/GPT/综述] AI Agent的设计模式综述
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
点击右上角即可分享
微信分享提示