Monostate的基础只是Singleton周围的语法糖。 开始子类化时,Monostate会变得有趣,因为子类可以用不同的行为来装饰共享状态。
一个简单的-如果有些人为的但不是很有效:)-示例:
public class GlobalTable implements Iterable {
/** Shared state -- private */
private static final Map MAP = new LinkedHashMap();
/** Public final accessor */
public final Value get(Key key) {
return MAP.get(key);
}
/** Public final accessor */
public final boolean put(Key key, Value value) {
return MAP.put(key);
}
/** Protected final accessor -- subclasses can use this to access
the internal shared state */
protected final Set keySet() {
return MAP.keySet();
}
/** Virtual -- subclasses can override for different behavior */
public Iterator iterator() {
return Collections.unmodifiableSet(MAP.keySet()).iterator();
}
}
现在如果我们想要索引访问怎么办?
public class IndexedGlobalTable extends GlobalTable {
public List getKeysAsList() {
return Collections.unmodifiableList(new ArrayList(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 iterator() {
return Collections
.unmodifiableSortedSet(new TreeSet(keySet())).iterator();
}
}
任何时候您需要一个或另一个数据视图时,都只需实例化相应的子类即可。
当然,首先要考虑全局数据是否真的是一个好主意,但这是另一个问题,但是至少Monostate为您提供了更多使用方式上的灵活性。