AdaptorManager.java

  1. /*
  2.  * @copyright defined in LICENSE.txt
  3.  */

  4. package hera.custom;

  5. import hera.Custom;
  6. import java.util.ArrayList;
  7. import java.util.HashSet;
  8. import java.util.List;
  9. import java.util.ServiceLoader;
  10. import java.util.Set;
  11. import lombok.Getter;

  12. public class AdaptorManager {

  13.   @Getter
  14.   protected static final AdaptorManager instance = new AdaptorManager();

  15.   protected Set<Adaptee<?>> initialized = new HashSet<Adaptee<?>>();

  16.   /**
  17.    * Get and return registered adaptees for {@code candidateClass}.
  18.    *
  19.    * @param <AdapteeT> adaptee type
  20.    * @param candidateClass adaptee type class
  21.    *
  22.    * @return adaptees
  23.    */
  24.   @SuppressWarnings("unchecked")
  25.   public <AdapteeT> List<? extends AdapteeT> getAdaptors(Class<AdapteeT> candidateClass) {
  26.     final ServiceLoader<Custom> serviceLoader = ServiceLoader.load(Custom.class);
  27.     final List<AdapteeT> list = new ArrayList<AdapteeT>();
  28.     for (final Custom custom : serviceLoader) {
  29.       if (candidateClass.isInstance(custom)) {
  30.         list.add((AdapteeT) custom);
  31.       }
  32.     }

  33.     for (final AdapteeT adaptee : list) {
  34.       if (adaptee instanceof Adaptee<?>) {
  35.         final Adaptee<?> custom = ((Adaptee<?>) adaptee);
  36.         if (!initialized.contains(custom)) {
  37.           custom.initialize(this);
  38.           initialized.add(custom);
  39.         }
  40.       }
  41.     }

  42.     return list;
  43.   }
  44. }