【发布时间】:2015-01-23 01:19:06
【问题描述】:
我对适配器模式有些困惑,想知道它是否是我想要完成的正确工具。
基本上,我试图让另一个开发人员编写的类符合我编写的接口,同时保留该类的其他方法。
所以我为容器对象编写了以下接口:
interface MyContainerInterface
{
public function has($key);
public function get($key);
public function add($key, $value);
public function remove($key);
}
我还编写了一个实现该接口的适配器:
class OtherContainerAdapter implements MyContainerInterface
{
protected $container;
public function __construct(ContainerInteface $container) {
$this->container = $container;
}
public function has($key) {
$this->container->isRegistered($key);
}
...
}
我在课堂上使用它如下:
class MyClass implements \ArrayAccess
{
protected $container;
public function __construct(MyContainerInterface $container) {
$this->setContainer($container);
}
public function offsetExists($key) {
$this->container->has($key);
}
...
}
然后我的应用程序使用该类:
$myClass = new MyClass(new OtherContainerAdapter(new OtherContainer));
我遇到的问题是,为了使用适配器中的方法,我必须编写以下内容:
$myClass->getContainer()->getContainer()->has('some_key');
理想情况下应该是:
$myClass->getContainer()->has('some_key');
【问题讨论】:
标签: php inheritance design-patterns containers adapter