使用C#設計Fluent Interface

咱們常用的一些框架例如:EF,Automaper,NHibernate等都提供了很是優秀的Fluent Interface, 這樣的API充分利用了VS的智能提示,並且寫出來的代碼很是整潔。咱們如何在代碼中也寫出這種Fluent的代碼呢,我這裏介紹3總比較經常使用的模式,在這些模式上稍加改動或者修飾就能夠變成實際項目中可使用的API,固然若是沒有設計API的需求,對咱們理解其餘框架的代碼也是很是有幫助。html

1、最簡單且最實用的設計框架

這是最多見且最簡單的設計,每一個方法內部都返回return this; 這樣整個類的全部方法均可以一連串的寫完。代碼也很是簡單:ide

使用起來也很是簡單:測試

       public class CircusPerformer
    {
        public List<string> PlayedItem { get; private set; }

        public CircusPerformer()
        {
            PlayedItem=new List<string>();
        }
        public CircusPerformer StartShow()
        {
            //make a speech and start to show
            return this;
        }
        public CircusPerformer MonkeysPlay()
        {
            //monkeys do some show
            PlayedItem.Add("MonkeyPlay");
            return this;
        }
        public CircusPerformer ElephantsPlay()
        {
            //elephants do some show
            PlayedItem.Add("ElephantPlay");
            return this;
        }
        public CircusPerformer TogetherPlay()
        {
            //all of the animals do some show
            PlayedItem.Add("TogetherPlay");
            return this;
        }
        public void EndShow()
        {
            //finish the show
        }

調用:this

        [Test]
        public void All_shows_can_be_invoked_by_fluent_way()
        {
            //Arrange
            var circusPerformer = new CircusPerformer();
            
            //Act
            circusPerformer
                .MonkeysPlay()
                .ElephantsPlay()
                .StartShow()
                .TogetherPlay()
                .EndShow();

            //Assert
            circusPerformer.PlayedItem.Count.Should().Be(3);
            circusPerformer.PlayedItem.Contains("MonkeysPlay");
            circusPerformer.PlayedItem.Contains("ElephantsPlay");
            circusPerformer.PlayedItem.Contains("TogetherPlay");
        }

可是這樣的API有個瑕疵,馬戲團circusPerformer在表演時是有順序的,首先要調用StartShow(),其次再進行各類表演,表演結束後要調用EndShow()結束表演,可是顯然這樣的API無法知足這樣的需求,使用者能夠爲所欲爲改變調用順序。.net

如上圖所示,vs將全部的方法都提示了出來。翻譯

咱們知道,做爲一個優秀的API,要儘可能避免讓使用者犯錯,好比要設計private 字段,readonly 字段等都是防止使用者去修改內部數據從而致使出現意外的結果。設計

2、設計具備調用順序的Fluent APIorm

在以前的例子中,API設計者指望使用者首先調用StartShow()方法來初始化一些數據,而後進行表演,最後使用者方可調用EndShow(),實現的思路是將不一樣種類的功能抽象到不一樣的接口中或者抽象類中,方法內部再也不使用return this,取而代之的是return INext;htm

根據這個思路,咱們將StartShow(),和EndShow()方法抽象到一個類中,而將馬戲團的表演抽象到一個接口中:

      public abstract class Performer
    {
        public abstract ICircusPlayer CircusPlayer { get;  }
        public abstract ICircusPlayer StartShow();
        public abstract void EndShow();
    }
       public interface ICircusPlayer
    {
        IList PlayedItem { get;  }
        ICircusPlayer MonkeysPlay();
        ICircusPlayer ElephantsPlay();
        Performer TogetherPlay();
    }

有了這樣的分類,咱們從新設計API,將StartShow()和EndShow()設計在CircusPerfomer中,將馬戲團的表演項目設計在CircusPlayer中:

      public class CircusPerformer:Performer
    {
        private  ICircusPlayer _circusPlayer;

        override public ICircusPlayer CircusPlayer { get { return _circusPlayer; } }

        public override ICircusPlayer StartShow()
        {
            //make a speech and start to show
            _circusPlayer=new CircusPlayer(this);
            return _circusPlayer;
        }
      
        public override void EndShow()
        {
            //finish the show
        }
    }
      public class CircusPlayer:ICircusPlayer
    {
        private readonly Performer _performer;
        public  IList PlayedItem { get; private set; }

        public CircusPlayer(Performer performer)
        {
            _performer = performer;
            PlayedItem=new List();
        }

        public ICircusPlayer MonkeysPlay()
        {
            PlayedItem.Add("MonkeyPlay");
            //monkeys do some show
            return this;
        }

        public ICircusPlayer ElephantsPlay()
        {
            PlayedItem.Add("ElephantPlay");
            //elephants do some show
            return this;
        }

        public Performer TogetherPlay()
        {
            PlayedItem.Add("TogetherPlay");
            //all of the animals do some show
            return _performer;
        }
    }

這樣的API能夠知足咱們的要求,在馬戲團circusPerformer實例上只能調用StartShow()和EndShow()

調用完StartShow()後方可調用各類表演方法。

固然因爲咱們的API很簡單,因此這個設計還算說得過去,若是業務很複雜,須要考慮衆多的情形或者順序咱們能夠進一步完善,實現的基本思想是利用裝飾者模式和擴展方法,因爲園子裏的dax.net在很早前就發表了相關博客在C#中使用裝飾器模式和擴展方法實現Fluent Interface,因此你們能夠去看這篇文章的實現方案,該設計應該能夠說是終極模式,實現過程也較爲複雜。

3、泛型類的Fluent設計

泛型類中有個不算問題的問題,那就是泛型參數是沒法省略的,當你在使用var list=new List<string>()這樣的類型時,必須指定準確的類型string。相比而言泛型方法中的類型時能夠省略的,編譯器能夠根據參數推斷出參數類型,例如

             var circusPerfomer = new CircusPerfomerWithGenericMethod();
            circusPerfomer.Show<Dog>(new Dog());
            circusPerfomer.Show(new Dog());

若是想省略泛型類中的類型有木有辦法?答案是有,一種還算優雅的方式是引入一個非泛型的靜態類,靜態類中實現一個靜態的泛型方法,方法最終返回一個泛型類型。這句話很繞口,咱們不妨來看個一個畫圖板實例吧。

定義一個Drawing<TShape>類,此類能夠繪出TShape類型的圖案

    public class Drawing<TShape> where TShape :IShape
    {
        public TShape Shape { get; private set; }
        public  TShape Draw(TShape shape)
        {
            //drawing this shape
            Shape = shape;
            return shape;
        }
    }

定義一個Canvas類,此類能夠畫出Pig,根據傳入的基本形狀,調用對應的Drawing<TShape>來組合出一個Pig來

          public void DrawPig(Circle head, Rectangle mouth)
        {
            _history.Clear();
            //use generic class, complier can not infer the correct type according to parameters
            Register(
                new Drawing<Circle>().Draw(head),
                new Drawing<Rectangle>().Draw(mouth)
                );
        }

這段代碼自己是很是好懂的,並且這段代碼也很clean。若是咱們在這裏想使用一下以前提到過的技巧,實現一個省略泛型類型且比較Fluent的方法咱們能夠這樣設計:

首先這樣的設計要藉助於一個靜態類:

       public static class Drawer
    {
        public static Drawing<TShape> For<TShape>(TShape shape) where TShape:IShape
        {
            return new Drawing<TShape>();
        }
    }

而後利用這個靜態類畫一個Dog

          public void DrawDog(Circle head, Rectangle mouth)
        {
            _history.Clear();
            //fluent implements
            Register(
                Drawer.For(head).Draw(head),
                Drawer.For(mouth).Draw(mouth)
            );
        }

能夠看到這裏已經變成了一種Fluent的寫法,寫法一樣比較clean。寫到這裏我腦海中浮現出來了一句」費這勁幹嗎」,這也是不少人看到這裏要想說的,我只能說你徹底能夠把這當成是一種奇技淫巧,若是哪天遇到使用的框架有這種API,你能明白這是怎麼回事就行。

4、案例

寫到這裏我其實還想舉一個例子來講說這種技巧在有些狀況下是很經常使用的,你們在寫EF配置,Automaper配置的時候常常這樣寫:

     xx.MapPath(
                Path.For(_student).Property(x => x.Name),
                Path.For(_student).Property(x => x.Email),
                Path.For(_customer).Property(x => x.Name),
                Path.For(_customer).Property(x => x.Email),
                Path.For(_manager).Property(x => x.Name),
                Path.For(_manager).Property(x => x.Email)
                )

這樣的寫法就是前面的技巧改變而來,咱們如今設計一個Validator,假如說這個Validator須要批量對Model的字段進行驗證,咱們也須要定義一個配置文件,配置某某Model的某某字段應該怎麼樣,利用這個配置咱們能夠驗證出哪些數據不符合這個配置。

配置文件類Path的關鍵代碼:

      public class Path<TModel>
    {
        private TModel _model;
        public Path(TModel model)
        {
            _model = model;
        }
        public PropertyItem<TValue> Property<TValue>(Expression<Func<TModel, TValue>> propertyExpression)
        {
            var item = new PropertyItem<TValue>(propertyExpression.PropertyName(), propertyExpression.PropertyValue(_model),_model);
            return item;
        }
    }

爲了實現fluent,咱們還須要定義一個靜態非泛型類,

    public static class Path
    {
        public static Path<TModel> For<TModel>(TModel model)
        {
            var path = new Path<TModel>(model);
            return path;
        }
    }

定義Validator,這個類能夠讀取到配置的信息,

          public Validator<TValue> MapPath(params PropertyItem<TValue>[] properties)
        {
            foreach (var propertyItem in properties)
            {
                _items.Add(propertyItem);
            }
            return this;
        }

最後調用

          [Test]
        public void Should_validate_model_values()
        {

            //Arrange
            var validator = new Validator<string>();
            validator.MapPath(
                Path.For(_student).Property(x => x.Name),
                Path.For(_student).Property(x => x.Email),
                Path.For(_customer).Property(x => x.Name),
                Path.For(_customer).Property(x => x.Email),
                Path.For(_manager).Property(x => x.Name),
                Path.For(_manager).Property(x => x.Email)
                )
              .OnCondition((model)=>!string.IsNullOrEmpty(model.ToString()));
            
            //Act
            validator.Validate();

            //Assert
            var result = validator.Result();
            result.Count.Should().Be(3);
            result.Any(x => x.ModelType == typeof(Student) && x.Name == "Email").Should().Be(true);
            result.Any(x => x.ModelType == typeof(Customer) && x.Name == "Name").Should().Be(true);
            result.Any(x => x.ModelType == typeof(Manager) && x.Name == "Email").Should().Be(true);
        }

這樣的Fluent API語言更加清晰而且不失優雅, Path.For(A).Property(x=>x.Name).OnCondition(B),這句話能夠翻譯爲,對A的屬性Name設置條件爲B。

結束語:有了這些Fluent API設計方式,你們在設計本身的API時能夠設計出更優雅更符合語義的API,本文提供下載本文章所使用的源碼,vs2013建立,測試項目使用了Nunit和FluentAssertions,如需轉載請註明出處。

相關文章
相關標籤/搜索