繁体   English   中英

如何从父容器调用方法

[英]How to call method from parent container

我有包含其他容器的容器,其中可以包含其他容器,依此类推。 对象container1具有特殊的方法foo() ,我想从container3调用此方法。 我怎样才能做到这一点?

我考虑过Singleton设计模式,但是在我的程序中存在多个MyClass1类的MyClass1 我考虑过Delegate设计模式,但是container2不必对MyClass1 (不需MyClass1 )。

container1:MyClass1
|
+--container2:MyClass2
|  |
|  +---container3:MyClass3
|  |
|  +---container3:MyClass3
|
+---container4:MyClass4

您可以使用某种方式的依赖注入模式。

一个小例子:

interface FooContainer 
{
   function foo();
}

Class Injector
{
    private diContainer;

    static function getInstance() 
    {
       <singleton>
    }

    function addDependency(FooContainer $class, $key)  
    {
       $this->diContainer[$key] = $class;
    }

    function getDependency($key) 
    {
       return $this->diContainer[$key];
    }
}

Class Container1 implements FooContainer
{
    function foo()
    {
        echo "Foo"
    }
}

Class Container3
{
    private fooClass;

    function setFoo()
    {
        $this->fooClass = Injector::getInstance()->getDependency("foo");
        return $this;
    }

    function foo()
    {
        $this->fooClass->foo();
    }
}

你这样称呼它。

$container1 = new Container1();
/** do whatever you need */
Injector::getInstance()->addDependency($container1, "foo");    
$container3 = new Container3();    
$container3->setFoo()->foo();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM