라이브러리

[PHP] SplObserver::update - 제목으로부터 업데이트 수신




Observer 패턴


Observer 패턴은 객체 간의 의존성을 줄이고, 객체의 상태 변화를 관찰하고 반응하는 디자인 패턴입니다. 이 패턴은 객체의 상태가 변경되었을 때, 관련된 객체에 알리기 위해 사용됩니다.

SplObserver 인터페이스


PHP 7.2 부터 SplObserver 인터페이스가 제공됩니다. 이 인터페이스는 Observer 패턴을 구현하기 위한 기본적인 메서드를 제공합니다.

# SplObserver::update 메서드


`SplObserver::update` 메서드는 Observer 패턴에서 사용되는 메서드입니다. 이 메서드는 Observer가 객체의 상태가 변경되었을 때 호출됩니다.

#hostingforum.kr
php

interface SplObserver

{

    public function update(SplSubject $subject);

}



# SplSubject 인터페이스


`SplSubject` 인터페이스는 Observer 패턴에서 사용되는 메서드를 제공합니다. 이 인터페이스는 Observer가 객체의 상태를 변경할 수 있도록 합니다.

#hostingforum.kr
php

interface SplSubject

{

    public function attach(SplObserver $observer);

    public function detach(SplObserver $observer);

    public function notify();

}



예제


Observer 패턴을 사용하여 예제를 작성해 보겠습니다.

#hostingforum.kr
php

class WeatherStation implements SplSubject

{

    private $observers = [];

    private $temperature;

    private $humidity;



    public function attach(SplObserver $observer)

    {

        $this->observers[] = $observer;

    }



    public function detach(SplObserver $observer)

    {

        $this->observers = array_diff($this->observers, [$observer]);

    }



    public function notify()

    {

        foreach ($this->observers as $observer) {

            $observer->update($this);

        }

    }



    public function setTemperature($temperature)

    {

        $this->temperature = $temperature;

        $this->notify();

    }



    public function setHumidity($humidity)

    {

        $this->humidity = $humidity;

        $this->notify();

    }



    public function getTemperature()

    {

        return $this->temperature;

    }



    public function getHumidity()

    {

        return $this->humidity;

    }

}



class WeatherObserver implements SplObserver

{

    public function update(SplSubject $subject)

    {

        if ($subject instanceof WeatherStation) {

            $weatherStation = $subject;

            echo "현재 기온은 " . $weatherStation->getTemperature() . "도이고, 습도는 " . $weatherStation->getHumidity() . "%입니다.
";

        }

    }

}



$weatherStation = new WeatherStation();

$weatherObserver1 = new WeatherObserver();

$weatherObserver2 = new WeatherObserver();



$weatherStation->attach($weatherObserver1);

$weatherStation->attach($weatherObserver2);



$weatherStation->setTemperature(25);

$weatherStation->setHumidity(60);



$weatherStation->detach($weatherObserver2);



$weatherStation->setTemperature(30);

$weatherStation->setHumidity(70);



이 예제에서는 WeatherStation 클래스가 SplSubject 인터페이스를 구현하고, WeatherObserver 클래스가 SplObserver 인터페이스를 구현합니다. WeatherStation 클래스는 Observer 패턴을 사용하여 Observer에 알립니다. WeatherObserver 클래스는 WeatherStation 클래스의 상태가 변경되었을 때 알림을 받고, 상태를 출력합니다.
  • profile_image
    나우호스팅 @pcs8404 

    호스팅포럼 화이팅!

    댓글목록

    등록된 댓글이 없습니다.

  • 전체 8,985건 / 137 페이지

검색

게시물 검색