001 /*****************************************************************************
002 * Copyright (c) PicoContainer Organization. All rights reserved. *
003 * ------------------------------------------------------------------------- *
004 * The software in this package is published under the terms of the BSD *
005 * style license a copy of which has been included with this distribution in *
006 * the LICENSE.txt file. *
007 * *
008 * Idea by Rachel Davies, Original code by Aslak Hellesoy and Paul Hammant *
009 *****************************************************************************/
010
011 package org.picocontainer.behaviors;
012
013 import java.io.Serializable;
014
015 import org.picocontainer.Behavior;
016 import org.picocontainer.ComponentAdapter;
017 import org.picocontainer.ObjectReference;
018
019 /**
020 * <p>
021 * {@link ComponentAdapter} implementation that caches the component instance.
022 * </p>
023 * <p>
024 * This adapter supports components with a lifecycle, as it is a
025 * {@link Behavior lifecycle manager} which will apply the delegate's
026 * {@link org.picocontainer.LifecycleStrategy lifecycle strategy} to the cached
027 * component instance. The lifecycle state is maintained so that the component
028 * instance behaves in the expected way: it can't be started if already started,
029 * it can't be started or stopped if disposed, it can't be stopped if not
030 * started, it can't be disposed if already disposed.
031 * </p>
032 *
033 * @author Mauro Talevi
034 */
035 public class Cached<T> extends Stored<T> {
036
037 public Cached(ComponentAdapter delegate) {
038 this(delegate, new SimpleReference());
039 }
040
041 public Cached(ComponentAdapter delegate, ObjectReference instanceReference) {
042 super(delegate, instanceReference);
043 }
044
045 /**
046 * @author Aslak Hellesøy
047 */
048 public static class SimpleReference<T> implements ObjectReference<T>,
049 Serializable {
050 private T instance;
051
052 public SimpleReference() {
053 }
054
055 public T get() {
056 return instance;
057 }
058
059 public void set(T item) {
060 this.instance = item;
061 }
062 }
063
064 public String toString() {
065 return "Cached:" + super.toString();
066 }
067
068 }