/**
* Class Toy
*
* @describe 原有的接口
*
* @author nick
*
*/
abstract class Toy
{
public abstract function openMonth();
public abstract function closeMonth();
}
class Dog extends Toy
{
public function openMonth()
{
echo '狗张嘴';
}
public function closeMonth()
{
echo '狗闭嘴';
}
}
class Cat extends Toy
{
public function openMonth()
{
echo '猫张嘴';
}
public function closeMonth()
{
echo '猫闭嘴';
}
}
// 目标公司 红枣公司
interface RedTarget
{
public function doMonthOpen();
public function doMonthClose();
}
// 目标公司 绿枣公司
interface GreenTarget
{
public function operateMouth( $type = 0 );
}
// 红枣公司适配器
class ReaAdapter implements RedTarget
{
private $adaptee;
// 只是接受 Toy 的子类
public function __construct( Toy $adaptee )
{
$this->adaptee = $adaptee;
}
public function doMonthOpen()
{
$this->adaptee->openMonth();
}
public function doMonthClose()
{
$this->adaptee->closeMonth();
}
}
// 绿枣公司适配器
class GreenAdapter implements GreenTarget
{
private $adaptee;
public function __construct(Toy $adaptee) {
$this->adaptee=$adaptee;
}
public function operateMouth( $type = 0 )
{
if($type){
$this->adaptee->openMonth();
}else{
$this->adaptee->closeMonth();
}
}
}
class testDriver
{
public function run(){
// 实例化一个玩具
$adaptee_dog = new Dog();
// 红枣公司适配器
echo '红枣公司适配器';
$adapter_red = new ReaAdapter($adaptee_dog);
$adapter_red->doMonthOpen();
$adapter_red->doMonthClose();
// 绿枣公司适配器
$adaptee_green = new GreenAdapter($adaptee_dog);
$adaptee_green->operateMouth(1);
$adaptee_green->operateMouth(0);
}
}
$test = new testDriver();
$test->run();
PHP设计模式之-----适配器模式
最新推荐文章于 2025-11-24 14:10:54 发布
本文通过定义一个玩具类接口并实现狗和猫两个具体类,展示了如何使用适配器模式来使这些类符合不同公司的接口规范。红枣公司和绿枣公司的适配器分别实现了特定接口,从而能够调用玩具类的不同方法。
189

被折叠的 条评论
为什么被折叠?



