001: /*******************************************************************************
002: * Copyright (c) 2004, 2006 IBM Corporation and others.
003: * All rights reserved. This program and the accompanying materials
004: * are made available under the terms of the Eclipse Public License v1.0
005: * which accompanies this distribution, and is available at
006: * http://www.eclipse.org/legal/epl-v10.html
007: *
008: * Contributors:
009: * IBM Corporation - initial API and implementation
010: *******************************************************************************/package org.eclipse.ui.internal;
011:
012: import java.util.ArrayList;
013: import java.util.Iterator;
014: import java.util.List;
015:
016: /**
017: * Represents an object with state that will notifies a set of listeners
018: * whenever its state changes
019: */
020: public class Model {
021:
022: /**
023: * Current state of the model
024: */
025: private Object state;
026:
027: /**
028: * Set of objects that will be notified about state changes
029: */
030: private List views = new ArrayList(1);
031:
032: /**
033: * Creates a new model with the given initial state.
034: *
035: * @param initialState
036: */
037: public Model(Object initialState) {
038: state = initialState;
039: }
040:
041: /**
042: * Returns the current state of the model.
043: *
044: * @return the current model state
045: */
046: public Object getState() {
047: return state;
048: }
049:
050: /**
051: * Sets the current state of the model.
052: *
053: * @param newState the new state of the model
054: * @param toOmit change listener that should be omitted from change notifications (or null if all
055: * listeners should be notified).
056: */
057: public void setState(Object newState, IChangeListener toOmit) {
058: if (areEqual(newState, state)) {
059: return;
060: }
061:
062: state = newState;
063:
064: Iterator iter = views.iterator();
065: while (iter.hasNext()) {
066: IChangeListener next = (IChangeListener) iter.next();
067:
068: if (next != toOmit) {
069: next.update(true);
070: }
071: }
072: }
073:
074: private boolean areEqual(Object o1, Object o2) {
075: if (o1 == null) {
076: return o2 == null;
077: }
078: if (o2 == null) {
079: return false;
080: }
081:
082: return o1.equals(o2);
083: }
084:
085: /**
086: * Adds the given listener to the set of listeners that will be
087: * notified when the state changes.
088: *
089: * @param toAdd
090: */
091: public void addChangeListener(IChangeListener changeListener) {
092: changeListener.update(false);
093: views.add(changeListener);
094: }
095:
096: /**
097: * Stops this model from sending change events from the given listener.
098: *
099: * @param toRemove
100: */
101: public void removeChangeListener(IChangeListener changeListener) {
102: views.remove(changeListener);
103: }
104:
105: }
|