DI 불편함을 느끼는 코드

This commit is contained in:
=taesan
2019-12-27 14:22:49 +09:00
committed by taesan
parent 6cc3e63de6
commit 0bd0c97bac
6 changed files with 100 additions and 0 deletions

28
spring/di/Program.java Normal file
View File

@@ -0,0 +1,28 @@
package spring.di;
import spring.di.entity.Exam;
import spring.di.entity.NewlecExam;
import spring.di.ui.ExamConsole;
import spring.di.ui.GridExamConsole;
import spring.di.ui.InlineExamConsole;
public class Program {
public static void main(String[] args) {
Exam exam = new NewlecExam();
ExamConsole console = new InlineExamConsole(exam); // DI
//ExamConsole console = new GridExamConsole(exam);
/*
new InlineExamConsole(exam)
new FridExamConsole(exam)
같은 메서드를 호출하게되는 위 코드의 수정을 대신해줄 수 있도록 하는 기능이 Spring의 DI다.
*/
console.print();
}
}

View File

@@ -0,0 +1,6 @@
package spring.di.entity;
public interface Exam {
int total();
float avg();
}

View File

@@ -0,0 +1,22 @@
package spring.di.entity;
public class NewlecExam implements Exam {
private int kor;
private int eng;
private int math;
private int com;
@Override
public int total() {
// TODO Auto-generated method stub
return kor+eng+math+com;
}
@Override
public float avg() {
// TODO Auto-generated method stub
return total() / 4.0f;
}
}

View File

@@ -0,0 +1,5 @@
package spring.di.ui;
public interface ExamConsole {
void print();
}

View File

@@ -0,0 +1,21 @@
package spring.di.ui;
import spring.di.entity.Exam;
public class GridExamConsole implements ExamConsole {
private Exam exam;
public GridExamConsole(Exam exam) {
this.exam = exam;
}
@Override
public void print() {
System.out.println("┌──────────┬──────────┐");
System.out.println("│ total │ avg │");
System.out.println("├──────────┼──────────┤");
System.out.printf("│ %3d │ %3.2f │\n", exam.total(), exam.avg());
System.out.println("└──────────┴──────────┘");
}
}

View File

@@ -0,0 +1,18 @@
package spring.di.ui;
import spring.di.entity.Exam;
public class InlineExamConsole implements ExamConsole {
private Exam exam;
public InlineExamConsole(Exam exam) {
this.exam = exam;
}
@Override
public void print() {
System.out.printf("total is %d, avg is %f\n", exam.total(), exam.avg());
}
}