dev/Spring
[Spring] Di 따라하기 1
by dev_Step
2022. 6. 22.
class House{}
class WoodHouse extends House{}
class BrickHouse extends House{}
class Window{}
main{
// DI 따라하기 1단계
House h = new House();
//House 라는 객체를 사용하다가 WoodHouse 라는 객체를
//사용 하려면 2부분 모두 수정해야 한다.
WoodHouse wh = new WoodHouse();
//이러면 비지니스 로직을 수정해야 하는데
//이를 수정하기 위해 다음 단계로는 다형성을 이용하게 된다.
//그러면 1부분만 수정을 하면된다.
House wh2 = new WoodHouse();
House wh3 = new BrickHouse();
System.out.println("h = " + h);
System.out.println("wh = " + wh);
System.out.println("wh2 = " + wh2);
System.out.println("wh3 = " + wh3);
//더 나아가 객체 생성하는 부분을 메서드를 변경하여
//만들면 한 메서드를 통해서 객체를 생성하면된다.
House ww = getHouse();
System.out.println(" \n\n ww = " + ww);
//다음 단계로는 내부에서 정의하는게 아닌 외부 파일을 통해서
//객체 생성하는 방법을 한번 알아보자(Properties 파일을 통해)
House pw = (House)getObject("house");
House pw2 = (House)getObject("woodhouse");
House pw3 = (House)getObject("brickhouse");
Window window = (Window)getObject("window");
System.out.println("pw = " + pw);
System.out.println("pw2 = " + pw2);
System.out.println("pw3 = " + pw3);
}
static House getHouse(){
return new WoodHouse();
}
static Object getObject(String key) throws Exception{
Properties p = new Properties();
p.load(new FileReader("HouseConfig.txt"));
System.out.println(p.getProperty(key));
Class clazz = Class.forName(p.getProperty(key));
return clazz.newInstance();
}
}
h = com.fastcampus.ch3.testDi.House@5ef04b5
wh = com.fastcampus.ch3.testDi.WoodHouse@5f4da5c3
wh2 = com.fastcampus.ch3.testDi.WoodHouse@443b7951
wh3 = com.fastcampus.ch3.testDi.BrickHouse@14514713
ww = com.fastcampus.ch3.testDi.WoodHouse@69663380
com.fastcampus.ch3.testDi.House
com.fastcampus.ch3.testDi.WoodHouse
com.fastcampus.ch3.testDi.BrickHouse
com.fastcampus.ch3.testDi.Window
pw = com.fastcampus.ch3.testDi.House@6d5380c2
pw2 = com.fastcampus.ch3.testDi.WoodHouse@45ff54e6
pw3 = com.fastcampus.ch3.testDi.BrickHouse@2328c243