디자인패턴

Observer pattern(옵저버 패턴)

hik14 2022. 7. 18. 01:33

옵저버 패턴 정의

- 특정 객체의 상태가 변화하면 그 객체에 의존하는 다른 객체에게 알림이 가고 자동으로 내용이 갱신되는 방식으로 일대다 의존성을 정의합니다.

 

*주제와 관찰자 객체간의 느슨한 결합을 통해 구현한다. 

 

 

 

기본 인터페이스 

interface Observer {
    fun update()
}

interface Subject {
    fun registerObserver(observer: Observer)
    fun removeObserver(observer: Observer)
    fun notifyObserver()
}

주제(RoadTrafficCorporation) 및 상태(SubWaySchedule) 클래스

class SubWaySchedule(val num: Int, var start: String = "05:00", var end: String = "23:00")


class RoadTrafficCorporation : Subject {

    private val _scheduleList: MutableList<SubWaySchedule> =
        mutableListOf(
            SubWaySchedule(num = 1),
            SubWaySchedule(num = 2),
            SubWaySchedule(num = 3),
        )
    val scheduleList: List<SubWaySchedule>
        get() = _scheduleList
    
    private val _subscriber: MutableList<Observer> = mutableListOf()
    val subscriber: List<Observer>
        get() = _subscriber
    
    fun changeSchedule(num: Int, start: String, end: String){
        val schedule = _scheduleList[num-1]
        schedule.start = start
        schedule.end = end
        notifyObserver()
    }
    
    override fun registerObserver(observer: Observer) {
        _subscriber.add(observer)
    }
    
    override fun removeObserver(observer: Observer) {
        _subscriber.remove(observer)
    }
    
    override fun notifyObserver() =
        _subscriber.forEach { observer ->
            observer.update()
        }
}

관찰자 클래스 

class KaKaoMap(val rtc: RoadTrafficCorporation) : Observer {

    init {
        rtc.registerObserver(this)
    }

    override fun update(num: Int) {
        rtc.scheduleList[num]
        println("kakao::${rtc.scheduleList[num]} 시간표 변경")
    }
}

class NaverMap(val rtc: RoadTrafficCorporation) : Observer {

    init {
        rtc.registerObserver(this)
    }

    override fun update(num: Int) {
        rtc.scheduleList[num]
        println("naver::${rtc.scheduleList[num]} 시간표 변경")
    }
}

class GoogleMap(val rtc: RoadTrafficCorporation) : Observer {

    init {
        rtc.registerObserver(this)
    }

    override fun update(num: Int) {
        rtc.scheduleList[num]
        println("google::${rtc.scheduleList[num]} 시간표 변경")
    }
}
fun main() {

    val roadTrafficCorporation = RoadTrafficCorporation()

    val kaKaoMap = KaKaoMap(roadTrafficCorporation)
    val naverMap = NaverMap(roadTrafficCorporation)
    val googleMap = GoogleMap(roadTrafficCorporation)

    roadTrafficCorporation.changeSchedule(2, "06:00", "23:00")
    roadTrafficCorporation.removeObserver(kaKaoMap)

    println("---------------------------------------------------------------")
    roadTrafficCorporation.removeObserver(kaKaoMap)
    roadTrafficCorporation.changeSchedule(1,"05:00", "24:00")
}