dimanche 28 août 2016

How to use inversion of control to create plug and play code in java?

I want to create a Java SDK for my team which creates the ability for them to create say a simple Java Class ( a plugin of sorts), register it somewhere and have Java choose, during run time which java class plugin to use.

Let's take a trivial example: I have 3 Java classes. Inside each is a function that takes a string and prints out "Short Greeting" + inputStr, "Long Greeting" + inputStr, and "Blah" + inputStr) respectively. Say they all implement an interface.

I wanted a design where these classes would be registered somewhere and tomorrow someone else can write a 4th class which would print something else out (also implements same interface). The decision for which class to choose should be based on say a input from a user?

ie. I can say java -jar my.jar -inputString "John" -pluginName="long"

and the jar would instantiate the correct class and implement the correct logic.

I know that I can have a simple switch case statement or if else if and else logic but this was a trivial case and in reality I want my code to be modularized so future additions of plugins are completely separate from each other.

I was told to look into IOC and dependency injection but I didn't find any good tutorials online. Any help would be appreciated, thanks in advanced.

Aucun commentaire:

Enregistrer un commentaire