Made CapabilityService more resilient

Affects issues:
- Fixed #1356
This commit is contained in:
Risto Lahtela 2020-03-19 15:56:29 +02:00
parent 648cdb1a0c
commit f2ba301880
2 changed files with 9 additions and 41 deletions

View File

@ -16,7 +16,8 @@
*/
package com.djrapitops.plan.capability;
import java.util.Optional;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
/**
@ -39,8 +40,7 @@ public interface CapabilityService {
* @throws IllegalStateException If Plan is installed, but not enabled.
*/
static CapabilityService getInstance() {
return Optional.ofNullable(Holder.service)
.orElseThrow(() -> new IllegalStateException("CapabilityService has not been initialised yet."));
return new CapabilityService() {};
}
/**
@ -48,7 +48,9 @@ public interface CapabilityService {
*
* @param isEnabledListener The boolean given to the method tells if Plan has enabled successfully.
*/
void registerEnableListener(Consumer<Boolean> isEnabledListener);
default void registerEnableListener(Consumer<Boolean> isEnabledListener) {
ListHolder.ENABLE_LISTENERS.add(isEnabledListener);
}
/**
* Check if the API on the current version provides a capability.
@ -61,16 +63,7 @@ public interface CapabilityService {
return Capability.getByName(capabilityName).isPresent();
}
class Holder {
static CapabilityService service;
private Holder() {
/* Static variable holder */
}
static void set(CapabilityService service) {
Holder.service = service;
class ListHolder {
static List<Consumer<Boolean>> ENABLE_LISTENERS = new ArrayList<>();
}
}
}

View File

@ -16,8 +16,6 @@
*/
package com.djrapitops.plan.capability;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
/**
@ -29,32 +27,9 @@ import java.util.function.Consumer;
*/
public class CapabilitySvc implements CapabilityService {
private final List<Consumer<Boolean>> enableListeners;
private CapabilitySvc() {
Holder.set(this);
enableListeners = new ArrayList<>();
}
private static CapabilitySvc get() {
if (Holder.service == null) {
return new CapabilitySvc();
}
return (CapabilitySvc) Holder.service;
}
public static void initialize() {
get();
}
public static void notifyAboutEnable(boolean isEnabled) {
for (Consumer<Boolean> enableListener : get().enableListeners) {
for (Consumer<Boolean> enableListener : CapabilityService.ListHolder.ENABLE_LISTENERS) {
enableListener.accept(isEnabled);
}
}
@Override
public void registerEnableListener(Consumer<Boolean> enableListener) {
enableListeners.add(enableListener);
}
}