Created
September 17, 2012 19:38
-
-
Save djcsdy/3739313 to your computer and use it in GitHub Desktop.
This qualifies as IoC. You don’t need no stinkin’ framework.
This file contains hidden or 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
// 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