-
-
Notifications
You must be signed in to change notification settings - Fork 1
Create Singleton
Eric Lam edited this page Jun 13, 2022
·
1 revision
Singleton is a design pattern that keeps the instance one and only one forever.
With dependency injection, you won't need to create a static instance for singleton:
public class TesterSingleton {
private final Map<String, String> collection = new HashMap<>();
public void setKey(String key, String value){
this.collection.put(key, value);
}
public String getString(){
return this.collection.toString();
}
}
then register it in main class
@Override
public void bindServices(ServiceCollection serviceCollection) {
serviceCollection.addSingleton(TesterSingleton.class);
}
then you can use it with injectable instances
(spigot for example)
public class TesterLifeCycle implements ELDLifeCycle {
@Inject
private TesterSingleton singleton;
@Inject
private TestConfig config;
@Override
public void onEnable(JavaPlugin javaPlugin) {
singleton.setKey("abc", "xya");
singleton.setKey("xyz", "abc");
javaPlugin.getLogger().info(singleton.getString());
javaPlugin.getLogger().info(config.toString());
}
@Override
public void onDisable(JavaPlugin javaPlugin) {
javaPlugin.getLogger().info(singleton.getString());
javaPlugin.getLogger().info(config.toString());
}
}