簡體   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