zoukankan      html  css  js  c++  java
  • 工厂模式和IOC练习

    <?php
    
    Interface Tools
    {
        public function run();
    }
    
    Class Car implements Tools
    {
        public $name = 'car';
        public $wheels = 4;
    
        public function run()
        {
            return  "car runrun<br>";
        }
    
    }
    
    Class Walk implements Tools
    {
        public $name = 'walk';
    
        public function run()
        {
           return  "walk runrun<br>";
        }
    
        public function walktaget()
        {
            echo "taget";
        }
    }
    
    Class ToolsFactory
    {
        public function createTools($name)
        {
            switch ($name) {
                case 'Car':
                    return new Car();
                    break;
                case 'Walk':
                    return new Walk();
                    break;
                default:
                    exit('err No tools');  //发生错误即使后面的正确也不执行了
                    break;
            }
        }
    }
    
    
    Class Traveller
    {
        private $trafficTools;
    
        public function __construct($tool)
        {
            $factory = new ToolsFactory();
            $this->trafficTools = $factory->createTools($tool);
        }
    
        public function go()
        {
            if (isset($this->trafficTools) && is_object($this->trafficTools))
             return $this->trafficTools->run();
        }
    
    }
    
    $walkr = new Traveller('Walk');
    echo $walkr->go();
    $carr = new Traveller('Car');
    echo $carr->go();
    
    Class TravellerIoc
    {
        private $trafficTools;
    
        public function __construct(Tools $tool)
        {
            $this->trafficTools = $tool;
        }
    
        public function go()
        {
            return $this->trafficTools->run();
        }
    
    }
    
    $told = new TravellerIoc(new Car());
    
    $told2 = new TravellerIoc(new Walk());
    echo $told->go();
    echo $told2->go();
    
    $car1="ssss";
    
    $trt=new Traveller($car1);
    echo $trt->go();
    $car2=new Car();
    
    $trioc=new TravellerIoc($car2);
    echo $trioc->go();
    
    $walkl=new Walk();
    
    $trioc=new TravellerIoc($walkl);
    echo $trioc->go();


    工厂模式和IOC的例子

  • 相关阅读:
    tech 浅谈 Yield
    Python strip lstrip rstrip使用方法
    Python strip lstrip rstrip使用方
    Python 的学习脚印(1)
    python中列表的赋值
    python的re模块的sub方法
    Python的异常处理机制
    [python] shutil模块
    【ActiveMq】启动amq时遇到java.net.URISyntaxException: Illegal character in hostname at index处理方法
    【sql总结】
  • 原文地址:https://www.cnblogs.com/cs88/p/6309032.html
Copyright © 2011-2022 走看看