PHP Design Patterns Ed - adapter mode

Adapter for an existing class, but the case did not want to replace the interface changes. The decorative pattern like mode, but with different application purposes.
Benpian example:
United States electrical voltage is 110V, China is 220V, you want to use Chinese electrical appliances in the United States, there should be a 110V adapter into 220V, otherwise electrical appliances can not be used. (Emmm, how to read it strange, but I have no evidence)

The first way: Object Adapter

interface Target
{
    public function volt110();
    public function other();
    public function volt220();
}

/**
 * Class Adaptee 被适配者
 */
class Adaptee
{
    public function volt110()
    {
        echo '110V<br>';
    }

    public function other()
    {
        echo '我是其它操作<br>';
    }
}

/**
 * Class Adapter 适配器
 */
class Adapter implements Target
{
    private $_adaptee;

    public function __construct(Adaptee $adaptee)
    {
        $this->_adaptee = $adaptee;
    }

    public function volt110()
    {
        $this->_adaptee->volt110();
    }

    public function other()
    {
        $this->_adaptee->other();
    }

    public function volt220()
    {
        echo '220V<br>';
    }

}
$adapter = new Adapter(new Adaptee());
$adapter->volt110(); // 想用110V就用110V,该类(Adaptee)在系统已存在并大规模使用了,修改它的逻辑判断与传参,可能会导致某些地方异常。
$adapter->volt220(); // 想用220V就增加22OV,在需要增加新的同类型操作时,但处理的数据不同,增加一个接口,再用适配器类(Adapter)实现该接口。使他们为同一个接口。
$adapter->other(); // 假装有其它操作

This can be called the same interface.
Do not do this, you need Adapteeto build a class of 220V (outside of class Adapter), when used again new. Now, before you add to the new interface just need to, you can call to unity.
In general, is the new class (the same method would have been able to put a class) Interface specification for a name, the classes to be added an interface, unified call.

The second way: class adapter. To better understand the above statement

interface Target2
{
    public function volt110();
    public function volt220();
}

class Adaptee2
{
    public function volt110()
    {
        echo '110V<br>';
    }

    public function other()
    {
        echo '我是其它操作<br>';
    }
}

class Adapter2 extends Adaptee2 implements Target2
{
    public function volt220()
    {
        echo '220V<br>';
    }
}

$adapter2 = new Adapter2();
$adapter2->volt110();
$adapter2->volt220();
$adapter2->other();
Published 112 original articles · won praise 75 · views 130 000 +

Guess you like

Origin blog.csdn.net/weikaixxxxxx/article/details/90729735