Last active
August 29, 2015 14:13
-
-
Save Ahnfelt/6ef713db4d5fe0113144 to your computer and use it in GitHub Desktop.
Frameworkless, minimal, typesafe Dependency Injection for Java.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface ShopService { | |
void buy(); | |
void sell(); | |
} | |
interface DatabaseService { | |
void beginTransaction(); | |
void commit(); | |
void abort(); | |
} | |
interface ShopLocator { ShopService shop(); } | |
interface DatabaseLocator { DatabaseService database(); } | |
class MyShopService<S extends DatabaseLocator> implements ShopService { | |
private final S services; | |
public MyShopService(S services) { | |
this.services = services; | |
} | |
@Override | |
public void buy() { | |
services.database().beginTransaction(); | |
services.database().commit(); | |
} | |
@Override | |
public void sell() { | |
services.database().beginTransaction(); | |
services.database().commit(); | |
} | |
} | |
class MyDatabaseService implements DatabaseService { | |
@Override public void beginTransaction() {} | |
@Override public void commit() {} | |
@Override public void abort() {} | |
} | |
// The class MyLocator is only mentioned somewhere in your Main file. | |
class MyLocator implements ShopLocator, DatabaseLocator { | |
private DatabaseService database = new MyDatabaseService(); | |
private ShopService shop = new MyShopService<>(this); | |
@Override | |
public DatabaseService database() { | |
return database; | |
} | |
@Override | |
public ShopService shop() { | |
return shop; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ShopService
/DatabaseService
define the services types of your system.ShopLocator
/DatabaseLocator
define methods that locate a particular type of service.MyShopService
example shows how to depend on aDatabaseService
. TheMyShopService
type is generic in the type parameterS
, which must extendDatabaseLocator
, eg. it must be able to provide aDatabaseService
.MyShopService
constructor takes an argument of theS
type and saves it. From then on, theservices
field can be used to locate the services thatS
extends locators for.MyShopService
also needed to depend onSomeService
, simply add it to the bound onS
, eg.S extends DatabaseLocator & SomeLocator
.MyLocator
class is just an example that provides a value of type? extends ShopLocator & DatabaseLocator
, eg. suitable as the constructor argument ofMyShopService
.ShopService shop = new MyShopService<>(this);
hides the type parameterS
, which is really only useful inside the implementation ofMyShopService
anyway.