01: /*
02: * Copyright 2001-2004 The Apache Software Foundation
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: package org.apache.commons.collections.comparators;
17:
18: import java.util.Comparator;
19:
20: import org.apache.commons.collections.Transformer;
21:
22: /**
23: * Decorates another Comparator with transformation behavior. That is, the
24: * return value from the transform operation will be passed to the decorated
25: * {@link Comparator#compare(Object,Object) compare} method.
26: *
27: * @since Commons Collections 2.0 (?)
28: * @version $Revision: 155406 $ $Date: 2005-02-26 12:55:26 +0000 (Sat, 26 Feb 2005) $
29: *
30: * @see org.apache.commons.collections.Transformer
31: * @see org.apache.commons.collections.comparators.ComparableComparator
32: */
33: public class TransformingComparator implements Comparator {
34:
35: /** The decorated comparator. */
36: protected Comparator decorated;
37: /** The transformer being used. */
38: protected Transformer transformer;
39:
40: //-----------------------------------------------------------------------
41: /**
42: * Constructs an instance with the given Transformer and a
43: * {@link ComparableComparator ComparableComparator}.
44: *
45: * @param transformer what will transform the arguments to <code>compare</code>
46: */
47: public TransformingComparator(Transformer transformer) {
48: this (transformer, new ComparableComparator());
49: }
50:
51: /**
52: * Constructs an instance with the given Transformer and Comparator.
53: *
54: * @param transformer what will transform the arguments to <code>compare</code>
55: * @param decorated the decorated Comparator
56: */
57: public TransformingComparator(Transformer transformer,
58: Comparator decorated) {
59: this .decorated = decorated;
60: this .transformer = transformer;
61: }
62:
63: //-----------------------------------------------------------------------
64: /**
65: * Returns the result of comparing the values from the transform operation.
66: *
67: * @param obj1 the first object to transform then compare
68: * @param obj2 the second object to transform then compare
69: * @return negative if obj1 is less, positive if greater, zero if equal
70: */
71: public int compare(Object obj1, Object obj2) {
72: Object value1 = this .transformer.transform(obj1);
73: Object value2 = this.transformer.transform(obj2);
74: return this.decorated.compare(value1, value2);
75: }
76:
77: }
|