《大话设计模式》中介者模式-联合国场景-PHP版代码

Standard

中介者模式
联合国场景

<?php
/**
 * 中介者模式 联合国场景
 * @author 叶茂盛 anson.ye#gmail.com  http://yemaosheng.com
 */
abstract class UnitedNations{
        abstract function Declares($message, Country $colleague);
}
 
abstract class Country{
        private $mediator;
 
        public function __construct(UnitedNations $mediator){
                $this->mediator = $mediator;
        }
        public function mediator(){
                return $this->mediator;
        }
}
 
class USA extends Country{
        public function __construct(UnitedNations $mediator){
                parent::__construct($mediator);
        }
        public function Declares($message){
                parent::mediator()->Declares($message, $this);
        }
        public function GetMessage($message){
                echo "美国获得对方信息:" . $message ."\n";
        }
}
class Iraq extends Country{
        public function __construct(UnitedNations $mediator){
                parent::__construct($mediator);
        }
        public function Declares($message){
                parent::mediator()->Declares($message, $this);
        }
        public function GetMessage($message){
                echo "伊拉克获得对方信息:" . $message ."\n";
        }
}
class UnitedNationsSecurityCouncil extends UnitedNations{
        private $colleague1;
        private $colleague2;
 
        public function __get($property_name){
                if(isset($this->$property_name)){
                        return($this->$property_name);
                }
                else{
                        return(NULL);
                }
        }
        public function __set($property_name, $value){
                $this->$property_name = $value;
        }
 
        public function Declares($message, Country $colleague){
                if($colleague == $this->colleague1){
                        $this->colleague2->GetMessage($message);
                }else{
                        $this->colleague1->GetMessage($message);
                }
        }
}
class Main{
        public static function run(){
                $UNSC = new UnitedNationsSecurityCouncil();
 
                $c1 = new USA($UNSC);
                $c2 = new Iraq($UNSC);
 
                $UNSC->colleague1 = $c1;
                $UNSC->colleague2 = $c2;
 
                $c1->Declares("不准研制核武器,否则就打你!");
                $c2->Declares("我们没有研制核武器,但也不怕你打!");
        }
}
Main::run();
?>
//php Mediator.php  
//伊拉克获得对方信息:不准研制核武器,否则就打你!
//美国获得对方信息:我们没有研制核武器,但也不怕你打!

转载请注明出处 http://yemaosheng.com

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.