class A
{
private B b;
public A(){
b = new B();
}
}
조립형 Association has a
A 안쪽이 아닌 외부에서 B라는 부품을 생성
결합력이 낮다 -> 부품(Dependency)을 갈아끼우기(업데이트하기) 편하다 = 기업형에서 주로 선호
※ 부품을 쉽게 바꿀 수 있지만 조립해야된다는 번거로움이 있다. -> spring이 갖고있는 기본능력 DI
class A
{
private B b;
public A(){
//b = new B();
}
public void setB(B b) {
this.b = b;
}
}
조립형의 두 가지 방법
B b = new B(); //new B() -> Dependency
A a = new A();
a.setB(b); //(b) -> Injection
Setter Injection
setter를 통해 조립
B b = new B();
A a = new A();
a.setB(b);
Construction Injection
생성자를 이용하여 조립
B b = new B();
A a = new A(b);
예제 1.
<자바코드에서 수작업으로 해보기>
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();
//InlineExamconsole, GridExamConsole이 exam객체를 조립 = DI
ExamConsole console = new InlineExamConsole(exam);
// ExamConsole console = new GridExamConsole(exam);
console.print();
}
}
package spring.di.entity;
public interface Exam {
int total();
float avg();
}
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() {
return kor + eng + math + com;
}
@Override
public float avg() {
return total() / 4.0f;
}
}
package spring.di.ui;
public interface ExamConsole {
void print();
}
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());
}
}
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.printf("%3d ///// %3.2f\n", exam.total(), exam.avg());
System.out.println("───────────────────");
}
}