KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > google > gwt > dev > generator > NameFactory


1 /*
2  * Copyright 2007 Google Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5  * use this file except in compliance with the License. You may obtain a copy of
6  * the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13  * License for the specific language governing permissions and limitations under
14  * the License.
15  */

16 package com.google.gwt.dev.generator;
17
18 import java.util.Set JavaDoc;
19 import java.util.HashSet JavaDoc;
20 import java.util.Collection JavaDoc;
21
22 /**
23  * Generates unqiue identifiers. Use this class to avoid generating
24  * conflicting names with user code. This class isn't smart enough to know
25  * about scopes (which isn't generally a problem for generators in any case).
26  */

27 public class NameFactory {
28
29   private final Set JavaDoc usedNames = new HashSet JavaDoc();
30
31   /**
32    * Creates a new <code>NameFactory</code> that knows about
33    * <code>existingNames</code>.
34    *
35    * @param existingNames a list of names that may be <code>null</code>.
36    */

37   public NameFactory(Collection JavaDoc existingNames) {
38     if (existingNames == null) {
39       return;
40     }
41     usedNames.addAll(existingNames);
42   }
43
44   /**
45    * Creates a new <code>NameFactory</code> that doesn't know about any existing
46    * names.
47    */

48   public NameFactory() {
49     this(null);
50   }
51
52   /**
53    * Adds a name to the set of already known identifiers. Has no affect if the
54    * name is already considered an existing identifier.
55    *
56    * @param name a not <code>null</code> name
57    */

58   public void addName(String JavaDoc name) {
59     usedNames.add(name);
60   }
61
62   /**
63    * Creates a new unique name based off of <code>name</code> and adds it to
64    * the list of known names.
65    *
66    * @param name a not <code>null</code> name to base the new unique name from
67    * @return a new unique, not <code>null</code> name. This name may be possibly
68    * identical to <code>name</code>.
69    */

70   public String JavaDoc createName(String JavaDoc name) {
71     String JavaDoc newName = name;
72
73     for (int count = 0; true; ++count) {
74       if (usedNames.contains(newName)) {
75         newName = name + count;
76       } else {
77         return newName;
78       }
79     }
80   }
81 }
82
Popular Tags