Java Reference
In-Depth Information
Tim Says. . .
One
Class
Can
Implement
Both
TypeConverter
and
Formatter
It is possible, and often desirable, to have a single class imple-
ment both the TypeConverter and Formatter interfaces. Type con-
version and formatting are really two sides of the same coin—
the processes of going from String to something more strongly
typed and back again.
Keeping all the code in one place can cut down on clutter
(fewer classes) and make maintenance simpler—if you modify
the target type, you can review a single class instead of two
to see whether changes are required. In addition, since you will
be dealing with the same classes, there may be common code
that can be more easily shared between the methods doing
type conversion and formatting. Lastly, since both interfaces
share the same setLocale(Locale) method, writing one class that
implements both means you have one less method to write!
Creating a custom type converter for Date is easily done by extending
DateTypeConverter . Earlier we saw that this converter does some pre-
processing and uses a series of formats to parse the input. These oper-
ations are implemented as protected methods so that subclasses can
easily make changes to the behavior:
protected Pattern getPreProcessPattern()
protected String preProcessInput(String input)
protected String checkAndAppendYear(String input)
protected String[] getFormatStrings()
protected DateFormat[] getDateFormats()
A TimeTypeConverter only has to override getFormatStrings ( ) to return the
"HH:mm" format:
Download data_types/src/stripesbook/opt/TimeTypeConverter.java
package stripesbook.opt;
public class TimeTypeConverter extends DateTypeConverter {
private static final String[] TIME_FORMAT = { "HH:mm" };
@Override
protected String[] getFormatStrings() {
return TIME_FORMAT;
}
}
 
Search WWH ::




Custom Search