dimanche 12 février 2017

Design pattern to decouple from third party lib

I am trying decouple a third party library's abstract class. I want to expose a new abstract class which will be exposed to the users rather than the library provided class.
I initially tried using an adapter but that stills add the import for the third party lib in the adapter class.

I added code below explaining my new approach.

   // third party lib
    abstract class ThirdParty<S> { 
       public abstract S doAction(S s);
    }
    // my goal here is to expose a different abstract class which is    decoupled from third party lib
    // exposed to other modules, rather than exposing the third party lib
    abstract class ExposedAbstractClass<S> {
        public abstract S doAction(S source);
        // get hold of type using guava lib
        private final TypeToken<S> typeToken = new TypeToken<S>(getClass()) { };
        public Class<S> getSourceClass() { return (Class<S>) typeToken.getClass()
    }

  // internal class
   class Builder<S> extends ThirdPartyLib<S> {
       ExposedAbstractClass exposed;
       public Builder(ExposedAbstractClass exposed) {
         this.exposed = exposed;
       }
       @Override
       public S doAction(S s) {
         return (S) exposed.doAction(s);
       }
   }
   //my approach breaks here when i try to invoke builder 
   class InvokeThirdParty {
       public void invoke (ExposedAbstractClass exposed) {
         Class type = exposed.getSourceClass();
         Builder<type> builder = new Builder(exposed); //doesn't work since Class is runtime type, and T is compile time type 
       }
   }

Any guidance in terms of which design pattern to follow here would be very helpful.

Aucun commentaire:

Enregistrer un commentaire