You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SingletonExtensionFactory.java 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Copyright (C) 2012-present the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.pf4j;
  17. import java.util.Arrays;
  18. import java.util.HashMap;
  19. import java.util.List;
  20. import java.util.Map;
  21. import java.util.WeakHashMap;
  22. /**
  23. * An {@link ExtensionFactory} that always returns a specific instance.
  24. * Optional, you can specify the extension classes for which you want singletons.
  25. *
  26. * @author Decebal Suiu
  27. * @author Ajith Kumar
  28. */
  29. public class SingletonExtensionFactory extends DefaultExtensionFactory {
  30. private final List<String> extensionClassNames;
  31. private Map<ClassLoader, Map<String, Object>> cache;
  32. public SingletonExtensionFactory(String... extensionClassNames) {
  33. this.extensionClassNames = Arrays.asList(extensionClassNames);
  34. cache = new WeakHashMap<>(); // simple cache implementation
  35. }
  36. @Override
  37. @SuppressWarnings("unchecked")
  38. public <T> T create(Class<T> extensionClass) {
  39. String extensionClassName = extensionClass.getName();
  40. ClassLoader extensionClassLoader = extensionClass.getClassLoader();
  41. if (!cache.containsKey(extensionClassLoader)) {
  42. cache.put(extensionClassLoader, new HashMap<>());
  43. }
  44. Map<String, Object> classLoaderBucket = cache.get(extensionClassLoader);
  45. if (classLoaderBucket.containsKey(extensionClassName)) {
  46. return (T) classLoaderBucket.get(extensionClassName);
  47. }
  48. T extension = super.create(extensionClass);
  49. if (extensionClassNames.isEmpty() || extensionClassNames.contains(extensionClassName)) {
  50. classLoaderBucket.put(extensionClassName, extension);
  51. }
  52. return extension;
  53. }
  54. }