aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorDecebal Suiu <decebal.suiu@gmail.com>2018-07-19 19:12:40 +0300
committerDecebal Suiu <decebal.suiu@gmail.com>2018-07-19 19:12:40 +0300
commit1f764c57cb61455ae2520ac50c6f2c5533a3d2f2 (patch)
tree3f86495c8b44b080dbe7a605cf195171df4c9d8b
parent834c8dade2005e9c074de47cb7c0e7fd06f03a12 (diff)
downloadpf4j-1f764c57cb61455ae2520ac50c6f2c5533a3d2f2.tar.gz
pf4j-1f764c57cb61455ae2520ac50c6f2c5533a3d2f2.zip
Add SingletonExtensionFactory (see #232)
-rw-r--r--pf4j/src/main/java/org/pf4j/SingletonExtensionFactory.java56
1 files changed, 56 insertions, 0 deletions
diff --git a/pf4j/src/main/java/org/pf4j/SingletonExtensionFactory.java b/pf4j/src/main/java/org/pf4j/SingletonExtensionFactory.java
new file mode 100644
index 0000000..d339921
--- /dev/null
+++ b/pf4j/src/main/java/org/pf4j/SingletonExtensionFactory.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2012-present the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.pf4j;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * An {@link ExtensionFactory} that always returns a specific instance.
+ * Optional, you can specify the extension classes for which you want singletons.
+ *
+ * @author Decebal Suiu
+ */
+public class SingletonExtensionFactory extends DefaultExtensionFactory {
+
+ private final List<String> extensionClassNames;
+
+ private Map<String, Object> cache;
+
+ public SingletonExtensionFactory(String... extensionClassNames) {
+ this.extensionClassNames = Arrays.asList(extensionClassNames);
+
+ cache = new HashMap<>(); // simple cache implementation
+ }
+
+ @Override
+ public Object create(Class<?> extensionClass) {
+ String extensionClassName = extensionClass.getName();
+ if (cache.containsKey(extensionClassName)) {
+ return cache.get(extensionClassName);
+ }
+
+ Object extension = super.create(extensionClass);
+ if (extensionClassNames.isEmpty() || extensionClassNames.contains(extensionClassName)) {
+ cache.put(extensionClassName, extension);
+ }
+
+ return extension;
+ }
+
+}