성적 산출하는 방법을 DI 를 사용하여 연습해보았다
public class program {
public static void main(String[] args) {
Exam exam = new Newlecexm();
exam 의 인터페이스를 생성한다.
package program.di.entity;
public interface Exam {
int total();
float avg();
}
Newlecexm 의 클래스를 생성한다.
국어, 영어, 수학, 컴퓨터과목에 대한 평균과 총점을 계산한다.
package program.di.entity;
public class Newlecexm 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;
}
}
exam 을 출력해주는 console을 정의한다.
public class program {
public static void main(String[] args) {
Exam exam = new Newlecexm();
ExamConsole console = new InlineExamConsole(exam);
console.print();
}
}
console의 인터페이스를 정의한다.
public interface ExamConsole {
void print();
}
InlineExamConsole 클래스
package program.di.ui;
import program.di.entity.Exam;
public class InlineExamConsole implements ExamConsole {
private Exam exam;
public InlineExamConsole(Exam exam) {
this.exam = exam;
}
@Override
public void print() {
// TODO Auto-generated method stub
System.out.printf("total is %d, avg is %f\n",exam.total(), exam.avg());
}
}
이번에는 그리드형식으로 나타내었다.
public class program {
public static void main(String[] args) {
Exam exam = new Newlecexm();
//ExamConsole console = new InlineExamConsole(exam);
ExamConsole console = new GridExamComsole(exam);
console.print();
}
}
public class GridExamComsole implements ExamConsole {
private Exam exam;
public GridExamComsole(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("└──────┴──────┘");
}
}