当前位置: 移动技术网 > IT编程>开发语言>c# > C#中设计、使用Fluent API

C#中设计、使用Fluent API

2019年07月18日  | 移动技术网IT编程  | 我要评论
我们经常使用的一些框架例如:ef,automaper,nhibernate等都提供了非常优秀的fluent api, 这样的api充分利用了vs的智能提示,而且写出来的代码

我们经常使用的一些框架例如:ef,automaper,nhibernate等都提供了非常优秀的fluent api, 这样的api充分利用了vs的智能提示,而且写出来的代码非常整洁。我们如何在代码中也写出这种fluent的代码呢,我这里介绍3总比较常用的模式,在这些模式上稍加改动或者修饰就可以变成实际项目中可以使用的api,当然如果没有设计api的需求,对我们理解其他框架的代码也是非常有帮助。

一、最简单且最实用的设计

这是最常见且最简单的设计,每个方法内部都返回return this; 这样整个类的所有方法都可以一连串的写完。代码也非常简单:

使用起来也非常简单:

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
   }

调用:

[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没法满足这样的需求,使用者可以随心所欲改变调用顺序。

如上图所示,vs将所有的方法都提示了出来。

我们知道,作为一个优秀的api,要尽量避免让使用者犯错,比如要设计private 字段,readonly 字段等都是防止使用者去修改内部数据从而导致出现意外的结果。

二、设计具有调用顺序的fluent api

在之前的例子中,api设计者期望使用者首先调用startshow()方法来初始化一些数据,然后进行表演,最后使用者方可调用endshow(),实现的思路是将不同种类的功能抽象到不同的接口中或者抽象类中,方法内部不再使用return this,取而代之的是return inext;

根据这个思路,我们将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,所以大家可以去看这篇文章的实现方案,该设计应该可以说是终极模式,实现过程也较为复杂。

三、泛型类的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,你能明白这是怎么回事就行。

四、案例

写到这里我其实还想举一个例子来说说这种技巧在有些情况下是很常用的,大家在写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。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网