samples/consistency/src-api2.0/api/Lookup.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 14 Jun 2008 10:04:53 +0200
changeset 210 acf2c31e22d4
parent 209 1c999569643b
permissions -rw-r--r--
Merge: Geertjan's changes to the end of the chapter
     1 package api;
     2 
     3 import java.util.ArrayList;
     4 import java.util.Collection;
     5 import java.util.Collections;
     6 import java.util.HashSet;
     7 import java.util.Iterator;
     8 import java.util.List;
     9 import java.util.Set;
    10 
    11 /** Simplified version of NetBeans 
    12  * <a href="http://bits.netbeans.org/6.0/javadoc/org-openide-util/org/openide/util/Lookup.html">Lookup</a>
    13  * reimplemented to separate the API for clients
    14  * from the API for implementators while guaranteeing
    15  * consistency among all there methods.
    16  *
    17  * @author Jaroslav Tulach <jtulach@netbeans.org>
    18  * @version 2.0
    19  */
    20 // BEGIN: design.consistency.2.0
    21 public abstract class Lookup {
    22     /** only for classes in the same package */
    23     Lookup() {
    24     }
    25     
    26     // BEGIN: design.consistency.lookup.2.0
    27     public <T> T lookup(Class<T> clazz) {
    28         Iterator<T> it = doLookup(clazz);
    29         return it.hasNext() ? it.next() : null;
    30     }
    31     // END: design.consistency.lookup.2.0
    32 
    33     // BEGIN: design.consistency.lookupAll.2.0
    34     public <T> Collection<? extends T> lookupAll(Class<T> clazz) {
    35         Iterator<T> it = doLookup(clazz);
    36         if (!it.hasNext()) {
    37             return Collections.emptyList();
    38         } else {
    39             List<T> result = new ArrayList<T>();
    40             while (it.hasNext()) {
    41                 result.add(it.next());
    42             }
    43             return result;
    44         }
    45     }
    46     // END: design.consistency.lookupAll.2.0
    47 
    48     // BEGIN: design.consistency.lookupAllClasses.2.0
    49     public <T> Set<Class<? extends T>> lookupAllClasses(Class<T> clazz) {
    50         Iterator<T> it = doLookup(clazz);
    51         if (!it.hasNext()) {
    52             return Collections.emptySet();
    53         } else {
    54             Set<Class<? extends T>> result = 
    55                 new HashSet<Class<? extends T>>();
    56             while (it.hasNext()) {
    57                 result.add(it.next().getClass().asSubclass(clazz));
    58             }
    59             return result;
    60         }
    61     }
    62     // END: design.consistency.lookupAllClasses.2.0
    63 // FINISH: design.consistency.2.0
    64     
    65     abstract <T> Iterator<T> doLookup(Class<T> clazz);
    66 }