服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 高级技术 > 设计模式 > 查看文档

校验值对象――应用visitor模式和反射

概要
值对象是一些单一的参数,用来联合一系列的对象――在大多数的情况下,在一个方法调用里有各种各样的参数。这些参数描述了一个大数量级的属性,通常,这些属性需要单独检测,而且大多数情况下是检测其是否为null。通常,这些检测带出来了大量的代码行。这篇文章描述了如何实现基于著名的visitor模式和反射的值对象。
 
在业务过程中,你通常有一些属性不能为空,而另外一些则没有这样的要求。在那些必须有实例的属性的案例中,你不得不实现如下所示的检测:
if( attribute1 == null )
{
     throw new attribute1isnullexception()
}
如果值对象有n个属性,你将会得到如下所示的代码:
if( attribute1 == null )
{
      throw new attribute1isnullexception()
}
if( attribute2 == null )
{
      throw new attribute2isnullexception()
}
...
if( attribute n == null )
{
      throw new attributenisnullexception()
}
结果:一大堆的if语句,但是你不得不把它们全部打出来。
现在假设校验的数量从10增加到25,因为有15个新增的用例必须在一个循环中实现。你是不是失去了勇气?用来减少这些检测的一个有效的方法是将他们从值对象类移到值对象的校验类。
从这个观点看来,你可能承认你永远执行相同的检测。唯一的不同是属性的名称和类型。在大多数情况下,类型不让人感兴趣,因为由编译器检测它。还有重要的一点需要确认:接收这些属性的值的方法都由同一个名称开始,在我们的案例中,是get。
通过反射调用这些值对象的getters方法非常简单。如果你使用eclipse,例如,你可以自动为所有的属性产品setters和getters方法。对于我们的attribute1,getter方法是getattribute1(),setter方法为setattribute1(integer attributevalue)。如果attribute1是integer类型的属性。如果这些前提给定了的话,你就能考虑一个一般的解决方案。这篇文章解释了如何使用visitor模式和反射来实现这个一般的解决方案。
 
框架类和接口
下面的类图显示了建立我们一般的校验框架需要用到的类和接口之间的关系:
注意:你可以从resources上下载这些类和接口
 
validateable接口
validateable接口有着和visitable接口相同的功能。那个定义的方法validatewith()是一个和visitor模式里的visitable接口的accept()方法相似的方法。通过validatewith()方法,你就能够校验有着不同validators的值对象,因为这个方法以iclassattributevalidator接口的实现作为参数。
 
iclassattributevalidator接口
iclassattributevalidator接口和visitor模式的visitor接口相对应。其中的validate(abstractparameter param)方法和visitor接口的visit(object someobject)方法相似。validate()方法的abstractparameter参数类型允许我们通过任何abstractparameter类的子类类型的参数访问validate。另外,在validatewith()方法里使用这个接口作为参数允许我们在将来改变使用的validator,用这些改变的validator作为来满足不同的validation的需求――例如,除了null检测以外,在一个定义的值范围测试参数属性。
 
abstractparameter
abstractparameter类实现了validateable接口的validatewith()方法。就像你将要看到的下面的代码片断一样,这个实现非常简单。这个方法仅仅是调用给定的validator的validate()方法,并且传递参数对象到validator:
public void validatewith( iclassattributevalidator validator ) throws exception
{
      validator.validate( this );
}
而且,abstractparameter也实现一些常用的其他方法。受保护的方法:addoptionalmethod()使得所有的子类型增加一些可选择的方法到optionalgetattributemethods hashmap()。继承自abstractparameter使得你能够取得哪些可能传递null的getters方法。就像你能想象到的一样,你能够增加可选择的方法,例如,到继承自abstractparameter的值对象的构造器里。
isoptionalmethod()方法用于检测属性是否已经被校验过了。
tostring()方法实现了一些便利,因为值对象可能是由很多属性组成。使得在abstractparameter的子类里,不需要写很多的system.out.printlns实现。这个方法也是使用反射达到目的的。
 
genericclassattributevalidator
genericclassattributevalidator类实现了iclassattributevalidator接口的validate()方法。这个类同时也实现了单态模式。validate()的实现看起来象下面这样:
public synchronized void validate( abstractparameter param ) throws attributevalidatorexception
{
      class clazz = param.getclass();
      method[] methods = clazz.getmethods();

      //cycle over all methods and call the getters!
      //check if the getter result is null.
      //if result is null throw attributevalidatorexception.
      iterator methoditer = arrays.aslist( methods ).iterator();
      method method = null;
      string methodname = null;

      while ( methoditer.hasnext() )
      {
            method = (method) methoditer.next();
            methodname = method.getname();

            if ( methodname.startswith( "get" ) &&
            clazz.equals( method.getdeclaringclass() ) &&
                 !param.isoptionalmethod( methodname ) )
            {
                 object methodresult = null;

                 try
                 {
                       methodresult = method.invoke( param, null );
                 }
                 catch ( illegalargumentexception e )
                 {
                       throw new attributevalidatorexception( e.getmessage() );
                 }
                 catch ( illegalaccessexception e )
                 {
                       throw new attributevalidatorexception( e.getmessage() );
                 }
                 catch ( invocationtargetexception e )
                 {
                       throw new attributevalidatorexception( e.getmessage() );
                 }

                 if ( methodresult == null )
                 {
                       string attributename = methodname.substring( 3, 4 ).tolowercase() +
                       methodname.substring( 4, methodname.length() );
                       string classname = clazz.getname();
                       classname = classname.substring( classname.lastindexof( '.' ) + 1 );

                       integer errornumber = new integer( 1000 );
                       throw new attributevalidatorexception( "error: " + errornumber + " "
                       + attributename + " in " + classname +" is null!!!");
                 }
            }
      }
}
首先,就像你在代码里看到的那样,我们从值对象里取得所有的方法。然后,我们遍历所有方法的集合。如果方法以get开头,便是abstractparameter的子类型,而不是可选择的方法。我们通过反射调用getter方法,并且检测它的结果。如果结果是null,那么这就是一个错误;如果不是,便是正常情况。那些可选择的方法和继承自父类的方法不会被执行。
 
测试我们的类
现在,我们实现了我们所需要的所有的类和接口。我们必须做一些测试来检验我们的类是否能够正常工作。为了做到这一点,我们写了一点小的测试类和一个main方法来运行测试。
 
testparameter
testparameter类继承自abstractparameter,并且包括了一些需要校验的私有属性:很简单的4个integer属性。
 
optional attributes
为了识别可选的属性没有被检测,我们定义了为属性:testparam3可选的getter方法。为了这个目的,我们通过testparameter的构造器里的addoptionalmethod(methodname)方法将这个getter方法输入到父类abstractparameter的可选方法map里。
 
校验框架是如何工作的
为了测试,我们在testparameter里使用如下方式输入:
testparameter param = new testparameter( );
param.settestparam1( new integer( 1 ) );
param.settestparam2( new integer( 2 ) );
param.settestparam3( new integer( 3 ) );
param.settestparam4( new integer( 4 ) );
就像你所看到的那样,4个integer属性记作integer1,2,3和4。为了校验,我们仅仅调用:param.validatewith( genericclassattributevalidator.getinstance( ) );
这个校验的结果是:
testparam1: 1
testparam2: 2
testparam4: 4
testparam3属性没有被校验,因为我们记录了它的getter方法为可选的。其他所有的方法得到了校验,并且结果是正常的。现在,我们希望看到其中的一个属性值为空,这样我们就能检测是否validator能够检测到这个错误。我们注释掉下面的行:
param.settestparam2( new integer( 2 ) );
我们重新开始测试以后,得到如下的结果:
testparam1: 1
error: testparam2 in testparameter is null!!!
testparam4: 4
现在我们看到了validator已经检测到了这个没有赋值的属性。
 
如果属性类型为集合类型,将会怎么样呢?
如果属性类型为集合,它仍然会检测这个集合是否为空。但是,可能检测集合是否为null并不是你想要的。在大多数情况下,你希望检测集合里的对象是否为null。如果集合的实现不允许null对象,你不需要关心这些在genericclassattributevalidator里的null对象继承自abstractparameter。一些为集合保持继承自abstractparameter的对象的辅助代码看起来如下所示:
if ( methodresult instanceof collection )
{
      collection col = (collection) methodresult;
      iterator iter = col.iterator();
      object subparam = null;

      while ( iter.hasnext() )
      {
            subparam = iter.next();

            if ( subparam instanceof abstractparameter )
            {
                 abstractparameter abstractparam = ( abstractparameter ) subparam;
                 abstractparam.validatewith( this );
            }
      }
}
集合里的所有没有继承自abstractparameter类的对象没有被检测,因为我们将使用一个不允许null对象的集合实现。所以集合实现为我们完成了检测。如果你决定使用一个允许null对象的实现,那么为while循环的所有其他的对象的一个额外的null检测就是必须的了:
else if( subparam == null )
{
      system.out.println( "error: subparameter not set in collection!" );
}
 
值之间的依赖
在一些情况下,只有当值对象的其他属性被分配了值,一个属性才有可能是可选的。属性的“可选性” sometimesoptional依赖于actiontype属性的值。可能action属性持有的值代表了actions:例如addsomething = 1, updatesomething = 2, 和 deletesomthing = 3。如果action的值是1或者3,sometimesoptional属性不是可选的;如果action的值是2,则是可选的。当我们为actiontype赋值的时候,我们必须设置sometimesoptional的可选性:
public void setactiontype(int actiontype)
{
      this.actiontype = actiontype;
      super.clearoptionalmethods( );
      switch( this.actiontype )
      {
            case actionparameter.action_add :
            super.addoptionalmethod( "getsometimesoptional4" );
            super.addoptionalmethod( "getsometimesoptional5" );
            break;
            case actionparameter.action_update :
            super.addoptionalmethod( "getsometimesoptional1" );
            break;
            case actionparameter.action_remove :
            super.addoptionalmethod( "getsometimesoptional1" );
            super.addoptionalmethod( "getsometimesoptional2" );
            super.addoptionalmethod( "getsometimesoptional3" );
            break;
            default :
            break;
      }
}
你会看到清除可选方法列表是必需的,因为如果你给actiontype赋值超过一次的话,越来越多的方法将作为可选的方法添加进来。另外的一个解决方法包括实现一个addactionparameter,一个updateactionparameter和一个removeactionparameter,它们都是从abstractparameter类继承得来。那么你可能不需要actiontype属性。但是拥有actiontype属性的类存在并且经常被使用,对该类使用反射非常容易,你必须使用switch语句。
 
展望
现在,我们可以考虑继承abstractparameter的更多的功能――例如,范围校验。abstractparamter需要一个数据结构来存储范围值。hashmap能够做到,它以方法名作为key存储范围对象。或者你可以检测是否一个string类型的值包含一些定义的字。等等。你也可以考虑perl 5的正则表达式。所有的这些检测都可以在validator类里实现,它实现了iclassattributevalidator接口。如果你想使用属性的null检测和附加值检测,那么你可以写一个子类来继承genericclassattributevalidator
j2ee应用里,值对象经常被用来在客户端和服务器之间传递业务过程的数据。但是,如果你仅仅在服务器端校验这些值对象的属性,你常常不得不因为一个错误的非可选属性为null而取消业务过程。你必须中断业务过程,而向客户端发送一个错误页面。这是一个好的实践:在服务端应用这些validators的同时,你也可以以委派的形式在客户端应用它们。在客户端检测值对象可以避免不必要的对服务器的请求和降低网络堵塞。
 
写一次,使用多次

扫描关注微信公众号