Spring DI 흉내내기
- 변경에 유리한 코드(1) - 다형성, factory method
//변경 포인트 2개
SportsCar car = new SportsCar();
--> Truck car = new Truck();
==>
//다형성 --> 변경에 유리
//변경 포인트 1개
Car car = new SportsCar();
--> Car car = new Truck();
==>
Car car = getCar(); // getCar()메서드 하나만 고치면 됨
static Car getCar() {
return new SportsCar();
}
- 변경에 유리한 코드(2) - Map과 외부 파일
Main1.java
package com.fastcampus.ch3.diCopy1;
import java.io.FileReader;
import java.util.Properties;
class Car {}
class Truck extends Car {}
class SportsCar extends Car{}
class Engine {}
public class Main1 {
public static void main(String[] args) throws Exception {
Car car = (Car)getObject("car");
Engine engine = (Engine)getObject("engine");
System.out.println("car = " + car);
System.out.println("engine = " + engine);
}
static Car getCar() throws Exception {
Properties p = new Properties();
p.load(new FileReader("config.txt"));
Class clazz = Class.forName(p.getProperty("car"));
return (Car)clazz.newInstance();
}
static Object getObject(String key) throws Exception {
Properties p = new Properties();
p.load(new FileReader("config.txt"));
Class clazz = Class.forName(p.getProperty(key));
return clazz.newInstance();
}
}
config.txt
car=com.fastcampus.ch3.diCopy1.SportsCar
engine=com.fastcampus.ch3.diCopy1.Engine