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