01: /*
02: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
03: */
04: package com.tc.config.schema.dynamic;
05:
06: import com.tc.util.Assert;
07: import com.tc.util.stringification.OurStringBuilder;
08:
09: /**
10: * A {@link ConfigItem} whose value is derived from one or more other {@link ConfigItem}s.
11: */
12: public abstract class DerivedConfigItem implements ConfigItem,
13: ConfigItemListener {
14:
15: private final ConfigItem[] derivedFrom;
16: private final CompoundConfigItemListener listener;
17:
18: private Object currentValue;
19:
20: public DerivedConfigItem(ConfigItem[] derivedFrom) {
21: Assert.assertNoNullElements(derivedFrom);
22: this .derivedFrom = derivedFrom;
23:
24: for (int i = 0; i < derivedFrom.length; ++i)
25: derivedFrom[i].addListener(this );
26:
27: this .listener = new CompoundConfigItemListener();
28: this .currentValue = createValueFrom(this .derivedFrom);
29: }
30:
31: public Object getObject() {
32: return currentValue;
33: }
34:
35: protected abstract Object createValueFrom(ConfigItem[] fromWhich);
36:
37: public void addListener(ConfigItemListener changeListener) {
38: this .listener.addListener(changeListener);
39: }
40:
41: public void removeListener(ConfigItemListener changeListener) {
42: this .listener.removeListener(changeListener);
43: }
44:
45: public void valueChanged(Object oldValue, Object newValue) {
46: Object ourOldValue = currentValue;
47: this .currentValue = createValueFrom(this .derivedFrom);
48:
49: if (((ourOldValue == null) != (this .currentValue == null))
50: || ((ourOldValue != null) && (!ourOldValue
51: .equals(this .currentValue)))) {
52: this .listener.valueChanged(ourOldValue, this .currentValue);
53: }
54: }
55:
56: public String toString() {
57: return new OurStringBuilder(this ,
58: OurStringBuilder.COMPACT_STYLE).append("derived from",
59: this.derivedFrom).toString();
60: }
61:
62: }
|