티스토리 뷰

웹개발/Php

옵저버패턴샘플

야쿠 yaku 2017.02.06 10:14
<?php

abstract class AbstractSubject
{
    abstract function attach(&$observer_in);

    abstract function detach($observer_in);

    abstract function notify();
}

abstract class AbstractObserver
{
    abstract function update($state);
}


class JSubject extends AbstractSubject
{

    var $_observers = array();

    var $_state = null;

    function notify()
    {
        foreach ($this->_observers as $observer) {
            $return[] = $observer->update($this->_state);
        }

        return $return;
    }

    function attach(&$observer)
    {
        if (is_object($observer)) {
            $class = get_class($observer);
            foreach ($this->_observers as $check) {
                if (is_a($check, $class)) {
                    return;
                }
            }
            $this->_observers[] = &$observer;
        } else {
            $this->_observers[] = &$observer;
        }
    }

    function detach($observer)
    {
        $retval = false;

        $key = array_search($observer, $this->_observers);

        if ($key !== false) {
            unset($this->_observers[$key]);
            $retval = true;
        }

        return $retval;
    }

    function getState()
    {
        return $this->_state;
    }

    function setState($state)
    {
        $this->_state = $state;
        $this->stateChanged();
    }

    function stateChanged()
    {
        $this->notify();
    }

}

abstract class Nobserver extends AbstractObserver
{
    public $_subject = null;
    public $_state = false;

    function __construct(& $subject)
    {
        $subject->attach($this);
        $this->_subject = &$subject;
    }

    function update($state)
    {
        $this->_state = $state;
        $this->display();
    }

}

class ob1 extends Nobserver
{

    function display()
    {
        echo " Observer 1 :   " . $this->_state . "\n";
    }
}

class ob2 extends Nobserver
{

    function display()
    {
        echo "  Observer 2 :   " . $this->_state . "\n";
    }
}

class ob3 extends Nobserver
{

    function display()
    {
        echo "  Observer 3 :   " . $this->_state . "\n";
    }
}

class ob4 extends Nobserver
{

    function display()
    {
        echo "  Observer 4 :   " . $this->_state . "\n";
    }
}

class ob5 extends Nobserver
{

    function display()
    {
        echo "  Observer 5 :   " . $this->_state . "\n";
    }
}

$subject = new JSubject();
$observer1 = new ob1($subject);
$observer2 = new ob2($subject);
$observer3 = new ob3($subject);
$observer4 = new ob4($subject);
$observer5 = new ob5($subject);


$subject->setState(444);

$subject->detach($observer2);

$subject->setState(111);
$subject->detach($observer5);


$subject->setState(666);


저작자 표시
신고

'웹개발 > Php' 카테고리의 다른 글

state 패턴 샘플  (0) 2017.02.06
데코레이터패턴 샘플  (0) 2017.02.06
옵저버패턴샘플  (0) 2017.02.06
Apater 패턴 샘플  (0) 2017.02.06
추상팩토리 패턴 샘플 소스  (0) 2017.02.06
PHP COOK Book 책 정리하기  (0) 2016.10.06
댓글
댓글쓰기 폼