다형성 방법 1
조상으로 정의된 변수의 값은 해당 자식 클래스들이 모두 올 수 있다.
그래서 다형성을 사용하면 코드의 변경을 줄일 수 있다.
예를 들어, Animal을 상속 받은 Cat과 Dog 클래스가 있다고 해보자
그럼 Animal animal = 값에는 Cat도 올 수도 있고 Dog도 올 수 있다.
즉, 조상의 클래스를 변수로 정의하면 해당 값에는 자식 클래스만 수정하면 된다.
만약 위와 같이 Animal이 아닌 직접 Cat으로 설정을 했을때 변경하고자 한다면 참조변수와 생성자 모두 바꿔야한다.
아래의 코드는 위의 설명을 적용한 예시이다.
다형성을 적용하지 않으면 직접 바꿔주어야한다.
* 변경 전
Cat animal1 = new Cat();
Cat animal2 = new Cat();
* 변경 후
Dog animal1 = new Dog();
Dog animal2 = new Dog();
만약 다형성을 적용해서 참조변수를 해당 조상으로 설정하면 변경할 항목이 아래와 같이 적어진다.
* 변경 전
Animal animal1 = new Cat();
Animal animal2 = new Cat();
* 변경 후
Animal animal1 = new Dog();
Animal animal2 = new Dog();
다형성 방법 2
변경에 있어 코드 수정을 덜 하게 하는 다형성의 방법 2번째는 메서드를 활용한 방법이다.
public static void main(String[] args) throws Exception {
//이렇게 하면 직접 new Cat을 하지 않고도 매서드만 호출하여 생성할 수 있음
Animal animal1 = (Animal)getObjectKey("dog");
Animal animal2 = (Animal)getObjectKey("cat");
//Animal이라는 조상이 있기 때문에 getObjectKey()매서드는 다형성이 적용되어, Animal을 조상으로 가진 클래스는 모두 적용된다.
System.out.println("animal1 = " + animal1);
System.out.println("animal2 = " + animal2);
}
static Object getObjectKey(String key){
if(key.equals("dog")) return new Dog();
else if (key.equals("cat")) return new Cat();
else return new Animal();
}
다형성 방법3
다형성의 세번째 방법은 Properties클래스를 사용하는 것이다.
Properties 클래스 적용할 경우 해당 소스코드를 직접 변경하지 않고 Properties를 적용할 config.txt 파일만 바꿔주면 된다.
그래서 새롭게 코드를 컴파일할 필요가 없어진다.
이때 config.txt 파일에서 사용하고자 하는 key = value 값을 지정한다. 이때 value는 원하는 클래스의 패키지명 포함하여 정의한다.
아래는 해당 config.txt 파일 내용이다.
cat=com.example.demo.di1.Cat
dog=com.example.demo.di1.Dog
animal=com.example.demo.di1.Cat
아래는 해당 config가 설정된 위치이다.
아래는 다형성 방법 3의 예제 코드이다.
public static void main(String[] args) throws Exception {
Animal animal3 = (Animal) getObjectProPerties("animal");
Dog dog = (Dog) getObjectProPerties("dog");
Cat cat = (Cat) getObjectProPerties("cat");
System.out.println("dog = " + dog);
System.out.println("cat = " + cat);
System.out.println("animal3 = " + animal3);
}
static Object getObjectProPerties(String key) throws Exception {
//Properties 클래스를 생성한다.
Properties prop = new Properties();
Class clazz= null;
//Properties의 매서드 load의 매개변수에 new FileReader("config.txt")를 선언해서 해당 파일을 읽어온다
prop.load(new FileReader("config.txt"));
//prop.getProperty(key);를 사용해서 해당 key의 value값을 불러온다.
//value 값은 클래스명(패키지포함)으로 설정되어 있다.
String className = prop.getProperty(key);
//Class.forName(패키지포함 클래스명)을 통해서 클래스를 불러온다.
clazz = Class.forName(className);
// 이 해당 클래스를 newInstance()를 통해 객체화 한다
return clazz.newInstance();
}
'spring' 카테고리의 다른 글
Spring DI(2) (0) | 2023.07.04 |
---|---|
URL 인코딩 (0) | 2023.05.11 |
HttpServletRequest 요청 값 받는 다양한 방법 (0) | 2023.02.01 |
Http Requset /Response (0) | 2023.01.16 |
스프링 @Controller 사용법 (0) | 2023.01.15 |
댓글