View Javadoc

1   /*
2    * $Id: SingletonObjectFactory.java 19855 2010-10-06 19:50:56Z aperepel $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.object;
12  
13  import org.mule.api.MuleContext;
14  import org.mule.api.lifecycle.InitialisationException;
15  
16  import java.util.Map;
17  
18  /**
19   * Creates an instance of the object once and then always returns the same instance.
20   */
21  public class SingletonObjectFactory extends AbstractObjectFactory
22  {
23      private Object instance;
24  
25      /**
26       * For Spring only
27       */
28      public SingletonObjectFactory()
29      {
30          super();
31      }
32  
33      public SingletonObjectFactory(String objectClassName)
34      {
35          super(objectClassName);
36      }
37  
38      public SingletonObjectFactory(String objectClassName, Map properties)
39      {
40          super(objectClassName, properties);
41      }
42  
43      public SingletonObjectFactory(Class objectClass)
44      {
45          super(objectClass);
46      }
47  
48      public SingletonObjectFactory(Class<?> objectClass, Map properties)
49      {
50          super(objectClass, properties);
51      }
52  
53      /**
54       * Create the singleton based on a previously created object.
55       */
56      public SingletonObjectFactory(Object instance)
57      {
58          super(instance.getClass());
59          this.instance = instance;
60      }
61  
62      @Override
63      public void dispose()
64      {
65          instance = null;
66          super.dispose();
67      }
68  
69      /**
70       * Always returns the same instance of the object.
71       * 
72       * @param muleContext
73       */
74      @Override
75      public Object getInstance(MuleContext muleContext) throws Exception
76      {
77          if (instance == null)
78          {
79              try
80              {
81                  instance = super.getInstance(muleContext);
82              }
83              catch (Exception e)
84              {
85                  throw new InitialisationException(e, this);
86              }
87          }
88          return instance;
89      }
90  
91      @Override
92      public Class<?> getObjectClass()
93      {
94          if (instance != null)
95          {
96              return instance.getClass();
97          }
98          else
99          {
100             return super.getObjectClass();
101         }
102     }
103 
104     @Override
105     public boolean isSingleton()
106     {
107         return true;
108     }
109 }