옵저버들의 목록을 객체에 등록해서 상태변화가 있을 때마다 메서드 등을 통해 객체가 직접 목록의 각 옵저버에게 알리도록 하는 디자인 패턴이다.
클래스 A 에서 B 의 이벤트를 수신받기 위해 클래스 B 를 인스턴스화 한 뒤, B 가 자신에게 이벤트가 발생할 때마다 클래스 A 가 갖고있는 메소드를 호출하도록 구현하면 된다.
인스턴스화 한다는 것은 쉽게 말하면 A가 B를 참조한다는 의미이다.
interface UpdateListener {
fun onUpdate()
}
class Plane(private var listener: UpdateListener) {
fun setBox(index: Int, box: Box) {
boxList[index] = box
listener.onUpdate()
}
}
class MainPresenter(override var view: MainContract.View, private var factory: BoxFactory) : MainContract.Presenter, UpdateListener {
override lateinit var plane: Plane
override fun loadBoxes() {
view.setBoxList(plane.getBoxList())
view.updateBoostCanvas()
view.setFocusIndex(plane.getFocusIndex())
view.setDragBox(plane.getDragBox())
val focusIndex = plane.getFocusIndex()
if (focusIndex != null) {
view.updateFocusInfo( plane.getBox(focusIndex))
} else {
view.updateFocusInfo(null)
}
}
override fun onUpdate() {
loadBoxes()
}
}
MainPresenter는 UpdateListener 인터페이스를 상속받고 있기 때문에, onUpdate()를 오버라이드 해준다. 이 함수가 호출되면 MainPresenter 내에 있는 loadBoxes()가 호출되면서 화면이 갱신된다.
Plane에서 속성이 바뀌면 갖고 있는 listener를 통해 listener.onUpdate()를 호출하게 되는데, 이는 MainPresenter의 onUpdate()를 호출한 것과 동일하다. 결국엔, loadBoxes() 호출을 끝으로 화면이 갱신된다.
이 포스팅은 MVP 패턴 구현해보기 와 연관되어 있다.