zoukankan      html  css  js  c++  java
  • php控制反转 依赖注入例子

    class Superman
    {
         protected $module;
         function __construct(PowerModule $PowerModule,array $arr)
         {
              $this->module = $PowerModule;
              echo "Superman is ready.
    ";
              $this->module->active($arr);
         }
    }
    
    interface PowerModule{
         public function active(array $target);
    }
    
    class XPower implements PowerModule
    {
         protected $long;
    
         public function active(array $target)
         {
              $this->long = $target[0];
              echo "XPower is ready.long is {$this->long}.
    ";
         }
    }
    
    
    class Boom implements PowerModule
    {
         protected $num;
    
         public function active(array $target)
         {
              $this->num = $target[0];
              echo "Boom is ready.num is {$this->num}.
    ";
         }
    }
    
    class Fly implements PowerModule
    {
         protected $speed;
         protected $height;
    
         public function active(array $target)
         {
              $this->num = $target[0];
              $this->speed = $target[0];
              $this->height = $target[1];
              echo "Fly is ready.speed is {$this->speed}.height is {$this->height}.
    ";
         }
    }
    
    class Ioc
    {
         protected $binds;
         protected $instance;
    
         public function bind($abstract,$concrete)
         {
              if ($concrete instanceof Closure)
              {
                   $this->binds[$abstract] = $concrete;
              }
              else
              {
                   $this->instance[$abstract] = $concrete;
              }
         }
    
         public function make($abstract,$params)
         {
              if (isset($this->instance[$abstract])) return $this->instance[$abstract];
              array_unshift($params, $this);
              return call_user_func_array($this->binds[$abstract], $params);
         }
    }
    
    $container = new Ioc();
    $container->bind('superman',function($container,$params){
    return new Superman($Boom,[3]);
    });
    $container->bind('boom',function($container){
    return new Boom();
    });
    
    $container->make('superman','boom');
    
    // $Boom = new Boom();
    // $man = new Superman($Boom,[3]);//这就是依赖注入
  • 相关阅读:
    使用jsonEditor打造一个复杂json编辑器
    【原创】一次“诡异”的容器Unix Socket通信问题分析
    【原创】Ingress-Nginx-Controller的Metrics监控源码改造简析
    IDEA+DevTools实现热部署功能
    ElementUI按需引入各种组件
    vue-cli4.0更新后怎样将eslint关闭
    Mysql修改字段名、修改字段类型
    博客搬家CSDN
    如何优雅的处理Restful
    java系列之注解
  • 原文地址:https://www.cnblogs.com/godehi/p/13087117.html
Copyright © 2011-2022 走看看