Created
August 8, 2018 09:01
-
-
Save Hwiggy/e431a2a364127c02d269ef673ab8fd33 to your computer and use it in GitHub Desktop.
How to do dependency injection
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
//This Dependency class will be our main class. | |
public class Dependency implements Dependable{ | |
//Create a Dependent object using the instance of this dependency in the constructor | |
private final Dependent dependent = new Dependent(this); | |
//Create an OtherDependent object using the instance of this dependency in the constructor | |
private final OtherDependent otherDependent = new OtherDependent(this); | |
//Create an OtherDependent object using the instance of the dependent object in the constructor | |
private final OtherDependent dependsDependent = new OtherDependent(dependent); | |
public static void main(String[] args){ | |
//Call all the Dependable methods | |
dependent.doSomething(); | |
otherDependent.doSomething(); | |
dependsDependent.doSometing(); | |
} | |
//This method overrides from the Dependable interface | |
@Override | |
public void doSomething(){ | |
System.out.println("Hey, you did something!"); | |
} | |
public static interface Dependable{ | |
public void doSomething(); | |
} | |
public static class Dependent implements Dependable{ | |
//The Dependency object stored as a field of this Dependent object | |
private final Dependency dependency; | |
public Dependent(Dependency dependency){ | |
//Assign the dependency field using the value from the constructor | |
this.dependency = dependency; | |
} | |
@Override | |
public void doSomething(){ | |
//Add custom behavior to the doSomething method, and call the method from Dependency | |
System.out.println("This was called from Dependent.java!"); | |
dependency.doSomething(); | |
} | |
} | |
public static class OtherDependent implements Dependable{ | |
//This class accepts any Dependable object to function as a dependency | |
private final Dependable dependency; | |
public OtherDependent(Dependable dependency){ | |
//Dependency assignment via constructor | |
this.dependency = dependency; | |
} | |
@Override | |
public void doSomething(){ | |
//Custom doSomething behavior as well as calling method from dependency | |
System.out.println("This was called from OtherDependent.java!"); | |
dependency.doSomething(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment