存放混合类型对象的JAVA容器
import java.util.*;
public class Favorites {
// Typesafe heterogeneous container pattern - implementation
private Map<Class<?>, Object> favorites =
new HashMap<Class<?>, Object>();
public <T> void putFavorite(Class<T> type, T instance) {
if (type == null)
throw new NullPointerException("Type is null");
favorites.put(type, instance);
}
public <T> T getFavorite(Class<T> type) {
return type.cast(favorites.get(type));
}
// Typesafe heterogeneous container pattern - client
public static void main(String[] args) {
Favorites favorites = new Favorites();
favorites.putFavorite(String.class, "StringResult");
favorites.putFavorite(Integer.class, 12);
favorites.putFavorite(Boolean.class, false);
System.out.println("results are: "
+ favorites.getFavorite(String.class)
+ favorites.getFavorite(Integer.class)
+ favorites.getFavorite(Boolean.class));
}
}
public class Favorites {
// Typesafe heterogeneous container pattern - implementation
private Map<Class<?>, Object> favorites =
new HashMap<Class<?>, Object>();
public <T> void putFavorite(Class<T> type, T instance) {
if (type == null)
throw new NullPointerException("Type is null");
favorites.put(type, instance);
}
public <T> T getFavorite(Class<T> type) {
return type.cast(favorites.get(type));
}
// Typesafe heterogeneous container pattern - client
public static void main(String[] args) {
Favorites favorites = new Favorites();
favorites.putFavorite(String.class, "StringResult");
favorites.putFavorite(Integer.class, 12);
favorites.putFavorite(Boolean.class, false);
System.out.println("results are: "
+ favorites.getFavorite(String.class)
+ favorites.getFavorite(Integer.class)
+ favorites.getFavorite(Boolean.class));
}
}