Java
[Interface] 인터페이스에 대한 수준낮은 고찰
고인돌개발자
2021. 4. 28. 13:43
학습목표 : 인터페이스가 낮은 수준에서 어떻게 구현되는지 알게된다.
시나리오 : 버스, 자가용, 자전거가 각각의 클락션 소리를 낸다고 가정한다.
1. MainSample.java
package interfacesample.ver1;
public class MainSample {
public static void main(String[] args) {
// TODO Auto-generated method stub
Bus bus = new Bus();
System.out.printf("Bus Sound : %s \n",bus.sound());
Car car = new Car();
System.out.printf("Car Sound : %s \n",car.sound());
Bike bike = new Bike();
System.out.printf("Bike Sound : %s \n",bike.sound());
}
}
// Bus Sound
class Bus{
public String sound() {
return "빠 ~~~앙";
}
}
// Car Sound
class Car{
public String sound() {
return "빵 빵";
}
}
// Bike Sound
class Bike{
public String sound() {
return "따릉 따릉";
}
}
# 위 프로그램의 경우 각각의 클래스를 객체화하여 사운드를 듣게한다.
2. MainSampleImprovement.java
package interfacesample.ver1;
import java.util.Scanner;
public class MainSampleImprovement {
public static void main(String[] args) {
// TODO Auto-generated method stub
IfSound s = new Bus();
Scanner scan = new Scanner(System.in);
while(true){
System.out.println("Input vehicle Sound : ");
String strSound = scan.next();
System.out.printf("Input value : %s \n", strSound);
if (strSound.equals("Bus")) { s = new Bus();
}else if (strSound.equals("Car")) { s = new Car();
}else if (strSound.equals("Bike")){ s = new Bike();
}
// 입력 받은 값이 어떤 값이든, 아래 구문의 s 참조변수는 그대로 사용 가능하다.
System.out.printf("Sound : %s \n",doSound(s));
}
}
public static String doSound(IfSound s) {
return s.sound();
}
}
// Interface
interface IfSound{
public String sound();
}
// Bus Sound
class Bus implements IfSound{
@Override
public String sound() {
return "빠 ~~~앙";
}
}
// Car Sound
class Car implements IfSound{
@Override
public String sound() {
return "빵 빵";
}
}
// Bike Sound
class Bike implements IfSound{
@Override
public String sound() {
return "따릉 따릉";
}
}
# 인터페이스를 사용하여, 어떤 입력값이 오더라도, 함수의 파라메터값을 동일하게 유지할 수 있는 확장성을 가진다.
# 해당 인터페이스이 구현체를 Di 로 구현하고 Interface 에서 @Autowire 로 구현하면 본문에서 구현체의 생성없이도 스프링에서 사용 가능한 구조가 된다.