package me.whiteship.designpatterns;
public class DependencyInjectionApp {
public static void main(String[] args) {
new Hi().greet();
}
}
class Hello {
public void greet() {
System.out.println("greetings from b");
}
}
class Hi {
public void greet() {
new Hello().greet();
}
}
public class DINotApplied {
public static void main(String[] args) {
Project project = new Project(new BackendDeveloper(), new FrontendDeveloper());
project.implement();
}
private static class BackendDeveloper {
public void writeJava() {
System.out.println("coding with java");
}
}
private static class FrontendDeveloper {
public void writeJs() {
System.out.println("coding with javascript");
}
}
private static class Project {
private final BackendDeveloper backendDeveloper;
private final FrontendDeveloper frontendDeveloper;
public Project(BackendDeveloper backendDeveloper,
FrontendDeveloper frontendDeveloper) {
this.backendDeveloper = backendDeveloper;
this.frontendDeveloper = frontendDeveloper;
}
public void implement() {
backendDeveloper.writeJava();
frontendDeveloper.writeJs();
}
}
}
package me.whiteship.designpatterns._04_di;
import java.util.ArrayList;
import java.util.List;
public class DIApplied {
public static void main(String[] args) {
List<Developer> developers = new ArrayList<>();
developers.add(new BackendDeveloper());
developers.add(new FrontendDeveloper());
Project project = new Project(developers);
project.implement();
}
interface Developer {
void develop();
}
static class BackendDeveloper implements Developer {
@Override
public void develop() {
writeJava();
}
void writeJava() {
System.out.println("coding with java");
}
}
static class FrontendDeveloper implements Developer {
@Override
public void develop() {
writeJs();
}
private void writeJs() {
System.out.println("coding with javascript");
}
}
static class Project {
private final List<Developer> developers;
public Project(List<Developer> developers) {
this.developers = developers;
}
public void implement() {
developers.forEach(Developer::develop);
}
}
}
의존 관계 역전 원칙(Inversion of Dependency Injection)