《大话设计模式》访问者模式-男人和女人场景-PHP版代码

Standard

访问者模式
男人和女人场景

<?php
/**
 * 访问者模式 男人和女人场景
 * @author 叶茂盛 anson.ye#gmail.com  http://yemaosheng.com
 */
abstract class Action{
        public abstract function GetManConclusion(Man $concreteElementA);
        public abstract function GetWomanConclusion(Woman $concreteElementB);
}
abstract class Person{
        public abstract function Accept(Action $visitor);
}
 
class Success extends Action{
        public function GetManConclusion(Man $concreteElementA){
                echo "男人".__CLASS__."时 背后多半有一个伟大的女人\n";
        }
        public function GetWomanConclusion(Woman $concreteElementB){
                echo "女人".__CLASS__."时 背后多半有一个不太成功的男人\n";
        }
}
class Failing extends Action{
        public function GetManConclusion(Man $concreteElementA){
                echo "男人".__CLASS__."时 闷头喝酒,谁也不用劝\n";
        }
        public function GetWomanConclusion(Woman $concreteElementB){
                echo "女人".__CLASS__."时 眼泪汪汪,谁也劝不了\n";
        }
}
class Amativeness extends Action{
        public function GetManConclusion(Man $concreteElementA){
                echo "男人".__CLASS__."时 凡事不懂也要装懂\n";
        }
        public function GetWomanConclusion(Woman $concreteElementB){
                echo "女人".__CLASS__."时 遇事懂也装作不懂\n";
        }
}
 
class Man extends Person{
        public function Accept(Action $visitor){
                $visitor->GetManConclusion($this);
        }
}
class Woman extends Person{
        public function Accept(Action $visitor){
                $visitor->GetWomanConclusion($this);
        }
}
 
class ObjectStructure{
        private $_elements;
 
        public function __construct(){
                $this->_elements = array();
        }
        public function Attach(Person $element){
                $this->_elements[ count($this->_elements) ] = $element;
        }
        public function Display(Action $visitor){
                foreach($this->_elements as $element){
                        $element->Accept($visitor);
                }
        }
}
 
class Main{
        public static function run(){
                $o = new ObjectStructure;
                $o->Attach(new Man());
                $o->Attach(new Woman());
 
                $v1 = new Success;
                $o->Display($v1);
 
                $v2 = new Failing;
                $o->Display($v2);
 
                $v3 = new Amativeness;
                $o->Display($v3);
        }
}
Main::run();
?>
//php Visitor.php 
//男人Success时 背后多半有一个伟大的女人
//女人Success时 背后多半有一个不太成功的男人
//男人Failing时 闷头喝酒,谁也不用劝
//女人Failing时 眼泪汪汪,谁也劝不了
//男人Amativeness时 凡事不懂也要装懂
//女人Amativeness时 遇事懂也装作不懂

转载请注明出处 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.