Basic example
The abstraction that defines the contract:package me.m1key.audioliciousmigration trait AudioliciousImporter { def importLibrary(libraryUuid: String): Unit }The implementation:
package me.m1key.audioliciousmigration.importer import me.m1key.audioliciousmigration.AudioliciousImporter private[audioliciousmigration] class RelativeDataImporter extends AudioliciousImporter { def importLibrary(libraryUuid: String): Unit = { println("Importing library [%s]...".format(libraryUuid)); println("Library [%s] imported.".format(libraryUuid)); } }Note package level private access - the implementation is not visible from the outside.
Here we bind implementations to abstractions:
package me.m1key.audioliciousmigration import com.google.inject.AbstractModule import com.google.inject.Provides import me.m1key.audioliciousmigration.importer.RelativeDataImporter class AudioliciousMigrationModule extends AbstractModule { @Override protected def configure() { bind(classOf[AudioliciousImporter]).to(classOf[RelativeDataImporter]) } }Finally, the bootstrap:
package me.m1key.audioliciousmigration import com.google.inject.Guice object Launcher { def main(args: Array[String]): Unit = { println("Audiolicious Importer") val injector = Guice.createInjector(new AudioliciousMigrationModule) val importer = injector.getInstance(classOf[AudioliciousImporter]) importer.importLibrary("UUID") println("Bye.") } }If you're new to Guice and you're confused, you can read more about it here.
In Part 3 I will show you how to create a singleton.
No comments:
Post a Comment