文章目录
适配器模式
意义在于让原本不能一起工作的类一起工作。
由:待适配 + 内部接口 + 适配器
/**
* 内部接口
* Interface Phone
*/
interface Phone
{
public function TypeC();
}
class Apple
{
public function Lightning()
{
return "连接成功,正在充电";
}
}
/**
* TypeC充电器+电源线
* Class power
*/
class Power
{
function charge(Phone $phone)
{
echo $phone->TypeC();
}
}
/**
* 适配器
* Class adapter
*/
class Adapter implements Phone
{
/**
* @var Apple
*/
public $phone;
function __construct()
{
$this->phone = new Apple();
}
public function TypeC()
{
return $this->phone->Lightning();
}
}
/**
* 我有华为的充电器+线支持type-c协议
* 本来是不能给apple充电的,但是我买了个万能转换器(Adapter)
* Adapter能支持type-c转Lightning
* 然后apple就能正常充电了
*/
$power = new Power();
$adapter = new Adapter();
$power->charge($adapter);