design patterns - Java multi-type method parameter? -


i wonder if possible require java method parameter of type finite set of types. example - using library 2 (or more) types have common methods, lowest common ancestor in type hierarchy object. mean here:

   public interface {       void mymethod();    }     public interface b {       void mymethod();    } ...    public void usemymethod(a a) {       // code duplication    }     public void usemymethod(b b) {       // code duplication    } 

i want avoid code duplication. think of this:

   public void usemymethod(a|b obj){       obj.mymethod();    } 

there similar type of syntax in java already. example:

  try{      //fail   } catch (illegalargumentexception | illegalstateexception e){      // use e safely here   } 

obviously not possible. how can achieve designed code using such type of uneditable type hierarchy ?

you write interface myinterface single method mymethod. then, each type want consider part of finite set, write wrapper class, this:

class wrapper1 implements myinterface {      private final type1 type1;      wrapper1(type1 type1) {         this.type1 = type1;     }      @override     public void mymethod() {         type1.method1();     } } 

then need use myinterface rather 1 of finite set of types, , appropriate method appropriate type called.

note use these wrapper classes call method mymethod have write

mymethod(new wrapper1(type1)); 

this going bit ugly going have remember name of wrapper class each type in set. reason, may prefer replace myinterfacewith abstract class several static factories produce wrapper types. this:

abstract class mywrapper {      static mywrapper of(type1 type1) {         return new wrapper1(type1);     }      static mywrapper of(type2 type2) {         return new wrapper2(type2);     }      abstract void mymethod(); } 

then can call method using code

mymethod(mywrapper.of(type1)); 

the advantage of approach code same no matter type use. if use approach have replace implements myinterface in wrapper1 declaration extends mywrapper.


Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -