01: /*****************************************************************************
02: * Copyright (C) PicoContainer Organization. All rights reserved. *
03: * ------------------------------------------------------------------------- *
04: * The software in this package is published under the terms of the BSD *
05: * style license a copy of which has been included with this distribution in *
06: * the LICENSE.txt file. *
07: * *
08: * Original code by *
09: *****************************************************************************/package org.picocontainer.gems.behaviors;
10:
11: import org.picocontainer.ComponentAdapter;
12: import org.picocontainer.PicoContainer;
13: import org.picocontainer.behaviors.Cached;
14:
15: /**
16: * This component adapter makes it possible to hide the implementation of a real subject (behind a proxy). If the key of the
17: * component is of type {@link Class} and that class represents an interface, the proxy will only implement the interface
18: * represented by that Class. Otherwise (if the key is something else), the proxy will implement all the interfaces of the
19: * underlying subject. In any case, the proxy will also implement {@link com.thoughtworks.proxy.toys.hotswap.Swappable}, making
20: * it possible to swap out the underlying subject at runtime. <p/> <em>
21: * Note that this class doesn't cache instances. If you want caching,
22: * use a {@link Cached} around this one.
23: * </em>
24: *
25: * @author Paul Hammant
26: */
27: public class HotSwappable extends HiddenImplementation {
28:
29: private final Swappable swappable = new Swappable();
30: private Object instance;
31:
32: public HotSwappable(ComponentAdapter delegate) {
33: super (delegate);
34: }
35:
36: protected Swappable getSwappable() {
37: return swappable;
38: }
39:
40: public Object swapRealInstance(Object instance) {
41: return swappable.swap(instance);
42: }
43:
44: public Object getRealInstance() {
45: return swappable.getInstance();
46: }
47:
48: public Object getComponentInstance(PicoContainer container) {
49: synchronized (swappable) {
50: if (instance == null) {
51: instance = super .getComponentInstance(container);
52: }
53: }
54: return instance;
55: }
56:
57: public String getDescriptor() {
58: return "HotSwappable";
59: }
60:
61: public static class Swappable {
62:
63: private transient Object delegate;
64:
65: public Object getInstance() {
66: return delegate;
67: }
68:
69: public Object swap(Object delegate) {
70: Object old = this.delegate;
71: this.delegate = delegate;
72: return old;
73: }
74:
75: }
76:
77: }
|