我们力求页面层代码简洁并具有较好的可读性,在ASP.NET MVC的平台上,我们以新的起点来实现这一目标.MvcContrib.FluentHtml和Spark ViewEngine给我们做出了榜样.本文将以MvcContrib.FluentHtml为例探究它的实现机制:Fluent Interface.
ASP.NET MVC
在MvcContrib.FluentHtml的应用中,我们随处可以见到下面的代码:
- <%=this.TextBox(x=>x.Person.Name).Title("Entertheperson'sname").Label("Name:")%><br/>
- ……
- <%=this.Select(x=>x.Person.Gender).Options(Model.Genders).Size(5).Label("Gender:")
- .Title("Selecttheperson'sgender")%><br/>
- <labelidlabelid="Person_Name_Label"for="Person_Name">Name:</label>
- <inputidinputid="Person_Name"type="text"value="Jeremy"title="Entertheperson'sname"name="Person.Name"maxlength="50"/>
- .
- <selectidselectid="Person_Gender"title="Selecttheperson'sgender"size="5"name="Person.Gender">
- <optionvalueoptionvalue="M"selected="selected">Male</option>
- <optionvalueoptionvalue="F">Female</option>
- </select>
这种实现编程方式就是"Fluent Interface",这并不是什么新概念,2005年Eric Evans 和Martin Fowler就为这种实现方式命名.源文档 <http://www.martinfowler.com/bliki/FluentInterface.html> 可以通过维基百科中对Fluent Interface的描述获得一个基本的了解:In software engineering, a fluent interface (as first coined by Eric Evans and Martin Fowler) is a way of implementing an object oriented API in a way that aims to provide for more readable code.
我们分解上面的话:
◆它是面向对象API的一种实现方式
◆目的是增加代码的可读性
既然我们最熟悉的是StringBuilder,我们就从这个线索追下去:打开Reflector,很容易找到StringBuilder的Append方法:
- publicStringBuilderAppend(stringvalue)
- {
- if(value!=null)
- {
- stringstringValue=this.m_StringValue;
- IntPtrcurrentThread=Thread.InternalGetCurrentThread();
- if(this.m_currentThread!=currentThread)
- {
- stringstringValue=string.GetStringForStringBuilder(stringValue,stringValue.Capacity);
- }
- intlength=stringValue.Length;
- intrequiredLength=length+value.Length;
- if(this.NeedsAllocation(stringValue,requiredLength))
- {
- stringnewString=this.GetNewString(stringValue,requiredLength);
- newString.AppendInPlace(value,length);
- this.ReplaceString(currentThread,newString);
- }
- else
- {
- stringValue.AppendInPlace(value,length);
- this.ReplaceString(currentThread,stringValue);
- }
- }
- returnthis;
- }
了解了Fluent Interface,我们来看一下MVCContrib.FluentHTML的实现,这里以TextBox为例进行考察,首先看一下它的继承关系:
public class TextBox : TextInput< TextBox>
public abstract class TextInput< T> : Input< T>, ISupportsMaxLength where T : TextInput< T>
public abstract class Input< T> : FormElement< T> where T : Input< T>, Ielement
泛型是一种高层次的算法抽象,我们就通过Input< T>一窥端倪:
- publicabstractclassInput<T>:FormElement<T>whereT:Input<T>,IElement
- {
- protectedobjectelementValue;
- protectedInput(stringtype,stringname):base(HtmlTag.Input,name)
- {
- builder.MergeAttribute(HtmlAttribute.Type,type,true);
- }
- protectedInput(stringtype,stringname,MemberExpressionforMember,
IEnumerable<IBehaviorMarker>behaviors)- :base(HtmlTag.Input,name,forMember,behaviors)
- {
- builder.MergeAttribute(HtmlAttribute.Type,type,true);
- }
- ///<summary>
- ///Setthe'value'attribute.
- ///</summary>
- ///<paramnameparamname="value">Thevaluefortheattribute.</param>
- publicvirtualTValue(objectvalue)
- {
- elementValue=value;
- return(T)this;
- }
- ///<summary>
- ///Setthe'size'attribute.
- ///</summary>
- ///<paramnameparamname="value">Thevaluefortheattribute.</param>
- publicvirtualTSize(intvalue)
- {
- Attr(HtmlAttribute.Size,value);
- return(T)this;
- }
- protectedoverridevoidPreRender()
- {
- Attr(HtmlAttribute.Value,elementValue);
- base.PreRender();
- }
- }
总结
为了能够在View中能够简洁清晰的构造HTML元素,ASP.NET MVC中通过htmlHelper.InputHelper来实现页面元素的构造. 页面层所使用的<%= Html.TextBox("username") %>,HTML也是htmlHelper的Extension Method.相比较起来,htmlHelper提供了基础的页面控件定义和构造,而FluentHTML表现的更为灵活.除了FluentHTML,著名的Spark View Engine也有类似的实现,大家可以关注一下.
【编辑推荐】