简体   繁体   中英

Easily switching between two different implementations of a java library?

I am currently working on a project that uses a third party library to manage hardware.

I wish to create a substitute library that presents the same interface, but instead of controlling actual hardware just presents a nice fake GUI. Preferably this can be done just by replacing the jar.

The problem is that all of the third party code is in the namespace edu.edu.wpi.first.wpilibj , and of course the namespace for my library is going to be very different.

Is there any way of easily switching implementations between the two libraries providing the same interface in java?

Yes, there are design patterns to do that.

You can look into Strategy pattern.

Even better you can look into Dependency injection .

You can use Google Guice as container and based on your configuration, at runtime, your implementation can switch between using N libraries.

At the end of the day, you need to wrap those libraries around some abstraction.

here is an example:

interface ISomeOperation{
    void process();
}

class ThatUsesTheWPILIBJ implements ISomeOperation{

    void process(){
      //use library here
    }

}

class ThatUsesYourMock implements ISomeOperation{
    void process(){
      //use your mock here
    }
}


public YourUIClass{

    private ISomeOperation _operatingClass;


    public YourUIClass(ISomeOperation  operatingClass){

        _operatingClass = operatingClass;
    }

    public void render(){
        _operatingClass.process();
    }
}

Now all you need to do is wiring. Look at google guice configuraion.

Yes. ServiceLoader . It allows to switch implementations by puting jar in classpath (or by some configuration). But it does not help with existing code. (But once done, switching to any other implementation is easy.

Its easy to library that uses it, but if library does not use it, it can be hard to introduce service loading. You would need to create service-loading wrapper. And if another library uses the original library, you would need to change and recompile it too.

Another approach would be puting it in same package as original library and mirror its public interface. But that is ugly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM