ObjectServerTree.java

/***************************************************************************
   Copyright 2012 Emily Estes

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
***************************************************************************/
package net.metanotion.scripting;


import net.metanotion.util.Dispatcher;

/** Create an object server instance that performs lookup on a hiearchy of ObjectServer instances.
This class is given a "self" and "parent" ObjectServer. When requests are made for scripting objects
the request is first looked up in the self object, if it's not found, the request is delegated to the parent.
*/
public final class ObjectServerTree implements ObjectServer {
	private final ObjectServer parent;
	private final ObjectServer self;

	/** Create an ObjectServer that delegates queries if an object can't be found.
		@param self The primary ObjectServer to perform lookups with.
		@param parent The ObjectServer to use if a request can't be found in the primary ObjectServer.
	*/
	public ObjectServerTree(final ObjectServer self, final ObjectServer parent) {
		this.self = self;
		this.parent = parent;
	}

	@Override public Dispatcher dispatcher(final String name) {
		final Dispatcher ret = self.dispatcher(name);
		if(ret != null) { return ret; }
		return parent.dispatcher(name);
	}

	@Override public Object get(final String name) {
		final Object ret = self.get(name);
		if(ret != null) { return ret; }
		return parent.get(name);
	}
}