1 /*
2 * Copyright (c) 2003-2008 by Cosylab d. d.
3 *
4 * This file is part of Java-Common.
5 *
6 * Java-Common is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * Java-Common is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with Java-Common. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 package com.cosylab.util;
21
22 import java.util.LinkedHashMap;
23 import java.util.Map;
24
25
26 /**
27 * Helper class that caches <code>PrintfFormat</code> classes. Used by table
28 * renderers, which need to switch between small number of different formats.
29 *
30 * @author <a href="mailto:ales.pucelj@cosylab.com">Ales Pucelj</a>
31 * @version $id$
32 */
33 public final class FormatCache
34 {
35 /** Default format string */
36 private static final String DEFAULT_FORMAT = "%+4.2f";
37 private static final int CACHE_LIMIT = 200;
38
39 /** Static cache of formatters */
40 private static final Map formatters = new LinkedHashMap();
41
42 /**
43 * Returns instance of <code>PrintfFormat</code>. If formatter does not
44 * already exist in cache, new instance will be created. If format is
45 * invalid, null will be returned.
46 *
47 * @param format C-Style format string.
48 *
49 * @return Instance of formatter or null if format string is invalid.
50 */
51 public static PrintfFormat getFormatter(String format)
52 {
53 Object o = formatters.get(format);
54
55 if (o == null) {
56 try {
57 if (format == null) {
58 o = getDefaultFormatter();
59 } else {
60 o = new PrintfFormat(format);
61 }
62 } catch (IllegalArgumentException e) {
63 return null;
64 }
65
66 formatters.put(format, o);
67
68 if (formatters.size() > CACHE_LIMIT) {
69 flush();
70 }
71 }
72
73 return (PrintfFormat)o;
74 }
75
76 /**
77 * Returns default formatter with format string %4.4f. This method will
78 * always return valid formatter.
79 *
80 * @return Instance of formatter with default format string %4.4f.
81 */
82 public static PrintfFormat getDefaultFormatter()
83 {
84 return getFormatter(DEFAULT_FORMAT);
85 }
86
87 /**
88 * Clears cache. This method will be periodically called to prevent
89 * excessive cache growth.
90 */
91 private static final void flush()
92 {
93 //formatters.clear();
94 while(formatters.size()>CACHE_LIMIT) {
95 formatters.remove(formatters.keySet().iterator().next());
96 }
97 }
98 }
99
100 /* __oOo__ */