UML图:
定义:将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
适配器的实现有两种方案:类适配(通过继承实现),对象适配(通过获得对象实现)
使用场景:当已有的类现在不能完成客户的需求,比如:一个两头充电器,现在需要这个充电器需要增加三头充电功能。要修改是比较简单的,直接在两头充电器类里面增加三头充电的方法就可以了。但是这样就要修改已有的类,这样是会影响之前的代码,不符合开闭原则。这个时候可以使用适配模式,目标接口是:具有二头充电功能,并且具有三头充电功能。
类适配实现代码:
//目标接口类 Plug.php
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2019/3/21
* Time: 9:21
*/
interface Plug
{
public function twoPinCharger();
public function threePinCharger();
}
//原有的二头充电器类 TwoPinPlug.php
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2019/3/21
* Time: 9:19
*/
class TwoPinPlug
{
public function twoPinCharger()
{
echo '两头充电器充电!';
}
}
//实现目标接口的具体类 PlugAdapter.php
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2019/3/21
* Time: 9:23
*/
require_once 'TwoPinPlug.php';
class PlugAdapter extends TwoPinPlug implements Plug
{
public function threePinCharger()
{
echo '三头充电器充电!';
}
}
//入口文件
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2019/3/21
* Time: 9:27
*/
header('Content-type:text/html;charset=utf8');
require_once 'Plug.php';
require_once 'PlugAdapter.php';
require_once 'TwoPinPlug.php';
$plug = new PlugAdapter();
$plug->twoPinCharger();
$plug->threePinCharger();
对象适配实现代码:
//目标接口类 Plug.php
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2019/3/21
* Time: 9:21
*/
interface Plug
{
public function twoPinCharger();
public function threePinCharger();
}
//原有的二头充电器类 TwoPinPlug.php
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2019/3/21
* Time: 9:19
*/
class TwoPinPlug
{
public function twoPinCharger()
{
echo '两头充电器充电!';
}
}
//实现目标接口的具体类 PlugAdapter.php
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2019/3/21
* Time: 9:23
*/
require_once 'TwoPinPlug.php';
class PlugAdapter implements Plug
{
private $twoPinPlug;
public function __construct(TwoPinPlug $t)
{
$this->twoPinPlug = $t;
}
public function threePinCharger()
{
echo '三头充电器充电!';
}
public function twoPinCharger()
{
$this->twoPinPlug->twoPinCharger();
}
}
//入口文件
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2019/3/21
* Time: 9:27
*/
header('Content-type:text/html;charset=utf8');
require_once 'Plug.php';
require_once 'PlugAdapter.php';
require_once 'TwoPinPlug.php';
$plug = new PlugAdapter(new TwoPinPlug());
$plug->twoPinCharger();
$plug->threePinCharger();