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.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. /**
  22. * An {@link ExtensionFactory} that always returns a specific instance.
  23. * Optional, you can specify the extension classes for which you want singletons.
  24. *
  25. * @author Decebal Suiu
  26. * @author Ajith Kumar
  27. */
  28. public class SingletonExtensionFactory extends DefaultExtensionFactory {
  29. private final List<String> extensionClassNames;
  30. private final Map<ClassLoader, Map<String, Object>> cache;
  31. public SingletonExtensionFactory(PluginManager pluginManager, String... extensionClassNames) {
  32. this.extensionClassNames = Arrays.asList(extensionClassNames);
  33. cache = new HashMap<>();
  34. pluginManager.addPluginStateListener(event -> {
  35. if (event.getPluginState() != PluginState.STARTED) {
  36. cache.remove(event.getPlugin().getPluginClassLoader());
  37. }
  38. });
  39. }
  40. @Override
  41. @SuppressWarnings("unchecked")
  42. public <T> T create(Class<T> extensionClass) {
  43. String extensionClassName = extensionClass.getName();
  44. ClassLoader extensionClassLoader = extensionClass.getClassLoader();
  45. if (!cache.containsKey(extensionClassLoader)) {
  46. cache.put(extensionClassLoader, new HashMap<>());
  47. }
  48. Map<String, Object> classLoaderBucket = cache.get(extensionClassLoader);
  49. if (classLoaderBucket.containsKey(extensionClassName)) {
  50. return (T) classLoaderBucket.get(extensionClassName);
  51. }
  52. T extension = super.create(extensionClass);
  53. if (extensionClassNames.isEmpty() || extensionClassNames.contains(extensionClassName)) {
  54. classLoaderBucket.put(extensionClassName, extension);
  55. }
  56. return extension;
  57. }
  58. }