다형성은 정말 편리한 기능이다.
인터페이스에도 다형성 기능을 활용해 더욱 편리한 기능을 제공해준다.
-
인터페이스 클래스 - Scheduler.java
package interfaceex; public interface Scheduler { public void getNextCall(); public void sendCallToAgent(); }
-기능 명세를 알려주는 추상메서드 2개를 선언하였다.
-
인터페이스 기능을 구현한 각 클래스들 정의
package interfaceex; public class RoundRobin implements Scheduler{ @Override public void getNextCall() { System.out.println("상담 전화를 순서대로 대기열에서 가져옵니다."); } @Override public void sendCallToAgent() { System.out.println("다음 순서 상담원에게 배분합니다."); } }
-인터페이스에 선언 된 기능을 구현하였다. 나머지들도 똑같으므로 생략.
-
테스트
package interfaceex; import java.io.IOException; public class SchedulerTest { public static void main(String[] args) throws IOException { System.out.println("전화 상담 할당 방식을 선택하세요."); System.out.println("R: 한명씩 차례로 할당"); System.out.println("L: 쉬고 있거나 대가가 가장 적은 상담원에게 할당"); System.out.println("P: 우선순위가 높은 고객 먼저 할당 "); System.out.println("A: 상담원이 직접 선택 "); int ch = System.in.read(); Scheduler scheduler = null; if(ch == 'R' || ch == 'r') { scheduler = new RoundRobin(); } else if(ch == 'L' || ch == 'l') { scheduler = new LeastJob(); } else if(ch == 'P' || ch == 'p') { scheduler = new Priorityallocation(); } else if(ch == 'A' || ch == 'a') { scheduler = new AgentGetCall(); } else { System.out.println("지원되지 않는 기능입니다."); } scheduler.getNextCall(); scheduler.sendCallToAgent(); } }
-기능은 간단하다. 다른 업무에 따라 해야하는 일들이 fix 에 되어있다.
-그렇지만 모두 Scheduler 클래스를 상속받았으므로, 다형성을 활용해 자료형을 Scheduler로 통일할 수 있다.
-만약 다형성이 없다면 각 클래스의 인스턴스를 만들어야 할 것이다.
-
만약 다형성이 없다면 ?
package interfaceex; import java.io.IOException; public class SchedulerTest2 { public static void main(String[] args) throws IOException { System.out.println("전화 상담 할당 방식을 선택하세요."); System.out.println("R: 한명씩 차례로 할당"); System.out.println("L: 쉬고 있거나 대가가 가장 적은 상담원에게 할당"); System.out.println("P: 우선순위가 높은 고객 먼저 할당 "); System.out.println("A: 상담원이 직접 선택 "); int ch = System.in.read(); if(ch == 'R' || ch == 'r') { RoundRobin instance1 = new RoundRobin(); instance1.getNextCall(); instance1.sendCallToAgent(); } else if(ch == 'L' || ch == 'l') { LeastJob instance2 = new LeastJob(); instance2.getNextCall(); instance2.sendCallToAgent(); } else if(ch == 'P' || ch == 'p') { Priorityallocation instance3 = new Priorityallocation(); instance3.getNextCall(); instance3.sendCallToAgent(); } else if(ch == 'A' || ch == 'a') { AgentGetCall instance4 = new AgentGetCall(); instance4.getNextCall(); instance4.sendCallToAgent(); } else { System.out.println("지원되지 않는 기능입니다."); } } }
-각 클래스의 인스턴스를 하나하나 다 선언해줘야한다 ㅜㅜ
- 출처: Do it 자바프로그래밍
'프로그래밍 > Java' 카테고리의 다른 글
기본클래스 - Object (0) | 2019.12.09 |
---|---|
인터페이스의 구현과 상속 (0) | 2019.12.08 |
인터페이스 - 디폴트메서드, 정적메서드 (0) | 2019.12.08 |
jdk환경변수 설정하기 (feat. window10) (0) | 2019.12.08 |
인터페이스 (0) | 2019.12.07 |