반응형
인터페이스(Interface)
일반적인 MVC 모델은 클래스끼리의 종속 관계가 있어 구현의 분업이 어렵다.
이러한 문제를 해결하기 위해 interface를 이용한다. interface를 이용하면 종속 클래스를 대신해 컴파일이 가능하기 때문이다.
다음과 같은 프로그램이 있다고 하자. 이것을 MVC(Model, View, Controller)로 팀을 분업해서 프로그래밍하기란 어려운 일이다. 따라서 인터페이스를 사용하여 이 프로그램을 분업화 한다면 아래 그림과 같이 설계도를 구성할 수 있다.
그리고 인터페이스 내부의 코드는 다음과 같다.
public interface SlidePuzzleBoardInterface {
public boolean move(int w);
public PuzzlePiece[][] board();
}
위의 그림과 같이 설계도를 변경할 수 있다. 그러면 클래스의 상속관계도 달라지기 때문에 Model을 구현하지 않아도 View와 Controller를 프로그래밍 할 수 있다.
클래스 계층구조(Class Hierarchy)
public class Person {
private String name;
public Person(String n) {
name = n;
}
public String name() {
return name;
}
public boolean sameName(Person other) {
return name.equals(other.name());
}
}
public class PersonFrom extends Person {
private String city;
public PersonFrom(String n, String c) {
super(n);
city = c;
}
public String city() {
return city;
}
public boolean same(PersonFrom other) {
return sameName(other) &&
city.equals(other.city());
}
}
Person p = new Person("마음");
Person q = new PersonFrom("소리", "서울");
이러한 코드가 있을 때 어떻게 될까. PersonFrom 클래스는 Person 클래스를 상속받고 있다. 따라서 p와 q는 컴파일러가 비교할 때 같은 Person 클래스 타입이므로 비교가 가능하지만 q의 경우 PersonFrom의 클래스를 사용한다면 에러가 발생한다.
# Implements를 사용할 때 주의점
- implements 클래스를 다른 클래스의 매개변수로 줄 때, implements는 상위 클래스이므로 컴파일 오류가 발생할 수 있다.
- 그 이유는 implements한 다른 자식 클래스들도 있기 때문이다.
- 이러한 경우 타입 캐스팅을 이용하여 변환해준다.
- 그러나 이러한 경우 다른 타입이 들어갔을 때 책임은 프로그래머에게 있다.
- implements는 부모 클래스이므로 자식 클래스의 필드나 메서드는 모른다.
728x90
반응형