Monostate本质上只是Singleton的一种语法糖。Monostate变得有趣的时候是当你开始子类化它,因为子类可以用不同的行为来修饰共享状态。
一个简单的例子(虽然有些牵强和效率不高 ^_^):
public class GlobalTable implements Iterable<Key> {
private static final Map<Key, Value> MAP = new LinkedHashMap<Key, Value>();
public final Value get(Key key) {
return MAP.get(key);
}
public final boolean put(Key key, Value value) {
return MAP.put(key);
}
protected final Set<Key> keySet() {
return MAP.keySet();
}
public Iterator<Key> iterator() {
return Collections.unmodifiableSet(MAP.keySet()).iterator();
}
}
现在,如果我们想要进行索引访问呢?
public class IndexedGlobalTable extends GlobalTable {
public List<Key> getKeysAsList() {
return Collections.unmodifiableList(new ArrayList<Key>(keySet()));
}
public Key getKeyAt(int index) {
return getKeysAsList().get(index);
}
public Value getValueAt(int index) {
return get(getKeyAt(index));
}
}
排序后的键如何处理?
public class SortedGlobalTable extends GlobalTable {
@Override
public Iterator <Key> iterator() {
return Collections
.unmodifiableSortedSet(new TreeSet<Key>(keySet())).iterator();
}
}
任何时候你需要数据的一个或另一个视图,只需实例化相应的子类即可。
当然,全局数据是否真的是一个好主意还是另一个问题,但至少单态模式使您在使用它时更加灵活。