| 本文还用到了聚合模式。java.util.Collection类的sort()方法只使用一个List和一个Comparator作参数。但是,我们希望基于一个comparator数组比较对象。通过创建一个我们的comparator,在内部顺序的调用其他的comparator,得以实现。如果你对这种聚合方式敢兴趣,请查看源代码。
简单的例子:使用我们的类
让我们看一个例子:类Car有三个属性:String color, double maxSpeed, boolean fourWheelDrive。
在你的应用中,可以支持基于上面三个属性作条件的搜索:用户可以输入喜欢的颜色查询,或者指定期望的最大速度。
你可能希望只显示颜色和最大时速,可能希望按照最大时速排序,第二排序是颜色。(实际上,你通常需要让用户决定选择什么,怎样排序。)
下面是实现上面功能的步骤:
1.定义对象数组或集合,并从数据源填充入对象。
Object[] data = getDataFromSomewhere();
或者:
Collection data = getDataFromSomewhere();
2.为你选择属性定义SelectInstruction:
//Define the Color column
Invoker colorInvoker = new Invoker(){
...public Object invoke(Object o){
......return ((Car)o).getColor();
...}
};
SelectInstruction colorSelectInstruction = new SelectInstruction("COLOR", colorInvoker);
//Define the maxSpeed column
Invoker speedInvoker = new Invoker(){
...public Object invoke(Object o){
......return new Integer(((Car)o).getMaxSpeed());
...}
};
SelectInstruction maxSpeedSelectInstruction = new SelectInstruction("MAXIMUM_SPEED", speedInvoker);
然后把这两个SelectInstruction对象加入SelectInstruction[]:
SelectInstruction [] instructions = new SelectInstruction [2];
instructions [0] = colorSelectInstruction;
in 上一页 [1] [2] [3] [4] [5] [6] [7] [8] 下一页 |