Skip to content

Instantly share code, notes, and snippets.

@djcsdy
Created September 17, 2012 19:38
Show Gist options
  • Save djcsdy/3739313 to your computer and use it in GitHub Desktop.
Save djcsdy/3739313 to your computer and use it in GitHub Desktop.
This qualifies as IoC. You don’t need no stinkin’ framework.
// This class acts as both the injector and the list of components.
//
// It contains a bit of boilerplate so although it’s easy to write it’s not great fun.
//
// It does have the advantage of being very straightforward to understand, and
// everything is static and checked at compile-time.
class Injector {
public static void main(String[] args) {
Repository repository = new RepositoryImpl();
PostBox postBox = new PostBoxImpl();
// IoC just means that you pass these dependencies into ChapImpl, instead of having
// ChapImpl construct them. Everything is static and checked by the compiler.
// There’s no need for any invisible magic.
Chap chap = new ChapImpl(repository, postbox);
}
}
interface Repository {
int getInt();
}
interface PostBox {
void postInt();
}
interface Chap {
}
class RepositoryImpl implements Repository {
public int getInt() {
return 1;
}
}
class PostBoxImpl implements PostBox {
private Repository repository;
private PostBox postBox;
public PostBox(Repository repository, PostBox postBox) {
this.repository = repository;
this.postBox = postBox;
}
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment