<?php
header('content-type:text/html;charset=utf-8');
/**
*适配器模式
*应用场景:主要应用于"希望复用一些现存的类,但是接口又和现状环境要求不一致的情况",在遗留代码复用,类库迁徙方面非常有用
*使用场景如下:
* 如api 升级 ,接口改变的时候,可以使用;
*面向对象规则之一:开闭原则;
*适配器模式核心思想:
*把对某些相似的类的操作转化为一个统一的“接口”(这里是比喻的说话)--适配器,或者比喻为一个“界面”,统一或屏蔽了那些类的细节。
*适配器模式还构造了一种“机制”,使“适配”的类可以很容易的增减,而不用修改与适配器交互的代码,符合“减少代码间耦合”的设计原则。
*
*/
#玩具类,基类;
abstract class Toy
{
abstract public function openMouth();
abstract public function closeMouth();
}
class Cat extends Toy
{
public function openMouth()
{
echo 'i am a cat ,i say cat language';
}
public function closeMouth()
{
echo 'i am a cat ,i will close my mouth';
}
}
class Dog extends Toy
{
public function openMouth()
{
echo 'i am a dog ,i say dog language';
}
public function closeMouth()
{
echo 'i am a dog ,i will close my mouth';
}
}
//2.目标角色接口;
interface RedTarget
{
public function doOpenMouth();
public function doCloseMouth();
}
interface GreenTarget
{
public function sing();
}
//3.适配器角色代码实现
class RedAdapter implements RedTarget
{
private $adaptee;
public function __construct(Toy $adaptee)
{
$this->adaptee = $adaptee;
}
public function doOpenMouth() //使得被适配类的接口转化成统一的接口调用
{
$this->adaptee->openMouth();
}
public function doCloseMouth() //使得被适配类的接口转化成统一的接口调用
{
$this->adaptee->closeMouth();
}
}
class GreenAdapter implements GreenTarget
{
protected $adaptee;
public function __construct(Toy $adaptee)
{
$this->adaptee = $adaptee;
}
public function sing()
{
echo $this->adaptee->openMouth() . '猫会爬树,你会吗?';
}
}
#调用方式#
$dog = new Dog();
$cat = new Cat();
$red_adapter = new RedAdapter($dog);
$red_adapter->doOpenMouth();
$red_adapter = new RedAdapter($cat);
$red_adapter->doOpenMouth();
exit;
$green_adapter = new GreenAdapter($cat);
$dog->openMouth();
$dog->closeMouth();
$red_adapter->doOpenMouth();
$green_adapter->sing();
###参考出处
http://www.cnblogs.com/whoknows/articles/adapter_in_php.html
大牛课堂
PHP设计模式之适配器模式
最新推荐文章于 2020-10-28 15:59:17 发布