Skip to content

Instantly share code, notes, and snippets.

@Hwiggy
Created September 30, 2020 20:29
Show Gist options
  • Save Hwiggy/4930280eda92536dfb279705c940473b to your computer and use it in GitHub Desktop.
Save Hwiggy/4930280eda92536dfb279705c940473b to your computer and use it in GitHub Desktop.
[Java] Dependency Injection
/**
* Dependency class for the Dependency Injection example.
*/
class Dependency {
/**
* The value enclosed inside this Dependency
*/
private final Object value;
/**
* Single-parameter constructor accepting an Object as a value for this Dependency
*/
public Dependency(Object value) {
// Use explicit this inside a constructor to reference the field when the field and parameter are named the same.
this.value = value;
}
/**
* Returns the Object value stored in this Dependency
*/
public Object getValue() { return value; }
}
/**
* Entrypoint class for the Dependency Injection example.
*/
class DependencyInjection {
/*
* Entrypoint method for the Dependency Injection example.
*/
public static void main(String[] args) {
// Create a new 'Dependency' to be used by 'Dependent' classes
// Dependency has a single parameter constructor for setting the enclosed value.
final Dependency dependency = new Dependency("Hello, World!");
// Create a new 'Dependent' using the created Dependency
// Dependent has a single parameter constructor for setting the Dependency to execute.
final Dependent dependent = new Dependent(dependency);
// Execute the dependent class
dependent.execute();
// Standard output: 'Hello, World!'
}
}
/**
* Dependent class for the Dependency Injection example.
*/
class Dependent {
/**
* The Dependency enclosed inside this Dependent
*/
private final Dependency dependency;
/**
* Single-parameter constructor accepting a Dependency as a dependency for this Dependent
*/
public Dependent(Dependency dependency) {
// Use explicit this inside a constructor to reference the field when the field and parameter are named the same.
this.dependency = dependency;
}
/**
* Print the stored Dependency's 'getValue' output to the standard output.
*/
public void execute() {
System.out.println(dependency.getValue());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment