How to implement the API/SPI Pattern in Java?
Posted
by
Adam Tannon
on Stack Overflow
See other posts from Stack Overflow
or by Adam Tannon
Published on 2012-07-09T22:38:29Z
Indexed on
2012/07/10
3:16 UTC
Read the original article
Hit count: 220
I am creating a framework that exposes an API for developers to use:
public interface MyAPI {
public void doSomeStuff();
public int getWidgets(boolean hasRun);
}
All the developers should have to do is code their projects against these API methods. I also want them to be able to place different "drivers"/"API bindings" on the runtime classpath (the same way JDBC or SLF4J work) and have the API method calls (doSomeStuff(), etc.) operate on different 3rd party resources (files, servers, whatever). Thus the same code and API calls will map to operations on different resources depending on what driver/binding the runtime classpath sees (i.e. myapi-ftp, myapi-ssh, myapi-teleportation).
How do I write (and package) an SPI that allows for such runtime binding, and then maps MyAPI calls to the correct (concrete) implementation? In other words, if myapi-ftp allows you to getWidgets(boolean) from an FTP server, how would I could this up (to make use of both the API and SPI)?
Bonus points for concrete, working Java code example! Thanks in advance!
© Stack Overflow or respective owner