这个例子是 java 编程思想——17.2.3 小节.使用 abstract 类。这个例子作者就是想,体现一下“享元”设计模式,大概意思就是容器的数据不一定非得存在容器内部。
package net.mindview.util;
import java.util.*;//删掉所有 import,改成*
public class Countries {
public static final String[][] DATA = new String[][]{{"ALGERIA", "Algiers"}, {"ANGOLA", "Luanda"}, {"BENIN", "Porto-Novo"}, {"BOTSWANA", "Gaberone"}, {"BURKINA FASO", "Ouagadougou"}, {"BURUNDI", "Bujumbura"}};//删掉了一些
static Map<String, String> map = new Countries.FlyweightMap((Countries.FlyweightMap)null);//这句不懂?
static List<String> names;
static {
names = new ArrayList(map.keySet());
}
public Countries() {
}
static Map<String, String> select(final int size) {
return new Countries.FlyweightMap() {
public Set<java.util.Map.Entry<String, String>> entrySet() {
return new Countries.FlyweightMap.EntrySet(size);
}
};
}
public static Map<String, String> capitals() {
return map;
}
public static Map<String, String> capitals(int size) {
return select(size);
}
public static List<String> names() {
return names;
}
public static List<String> names(int size) {
return new ArrayList(select(size).keySet());
}
public static void main(String[] args) {
Print.print(capitals(10));
Print.print(names(10));
Print.print(new HashMap(capitals(3)));
Print.print(new LinkedHashMap(capitals(3)));
Print.print(new TreeMap(capitals(3)));
Print.print(new Hashtable(capitals(3)));
Print.print(new HashSet(names(6)));
Print.print(new LinkedHashSet(names(6)));
Print.print(new TreeSet(names(6)));
Print.print(new ArrayList(names(6)));
Print.print(new LinkedList(names(6)));
Print.print(capitals().get("BRAZIL"));
}
//就是个静态内部类
private static class FlyweightMap extends AbstractMap<String, String> {
private static Set<java.util.Map.Entry<String, String>> entries;
static {
entries = new Countries.FlyweightMap.EntrySet(Countries.DATA.length);
}
private FlyweightMap() {
}
public Set<java.util.Map.Entry<String, String>> entrySet() {
return entries;
}
//太长了,省略
但这是通过 IDEA 查看 jar 包里面的 class 文件的反编译视角看的源码(当初只找到 net.mindview.util 的 jar 包,没找到它的源码),然后发现有个地方不大懂:
就是static Map<String, String> map = new Countries.FlyweightMap((Countries.FlyweightMap)null);
这句,这句到原书里面是static Map<String, String> map = new FlyweightMap();
原来只是调用默认构造器,现在是给默认构造器传一个强转后的null
,这是什么操作啊?(恕我愚昧,这个问题我确实没百度到)
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.