适配器模式-仿生机器人
(1)目标抽象类Robot(机器人接口)
interface Root
{
public function cry();
public function move();
}
(2)适配者类Dog(Dog类)
class Dog
{
public function wang()
{
echo '狗汪汪叫';
}
public function run()
{
echo '够快快跑';
}
}
(2)适配器类DogAdapter(DogAdapter类)
class DogAdapter extends Dog implements Root
{
public function cry()
{
echo '机器人模仿:';
parent::wang();
}
public function move()
{
echo '机器人模仿:';
parent::run();
}
}
(3)辅助代码,客户端测试类
class client
{
public function runing()
{
$animalstring = simplexml_load_file('animal.xml');
foreach ($animalstring as $animal ) {
eval("\$root = new {$animal->name}();");
$root->cry();
echo '<br>';
$root->move();
echo '<br>';
echo '<br>';
}
}
}
$client = new client();
$client->runing();
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<animal>
<Dog>
<name>DogAdapter</name>
</Dog>
</animal>
如果向系统添加 可通过以下为例添加
class Bird
{
public function tweedle()
{
echo '鸟儿叽叽叫';
}
public function fly()
{
echo '鸟儿快快飞';
}
}
class BirdAdapter extends Bird implements Root
{
public function cry()
{
echo '机器人模仿:';
parent::tweedle();
}
public function move()
{
echo '机器人模仿:';
parent::fly();
}
}
<Bird>
<name>BirdAdapter</name>
</Bird>
运行结果
机器人模仿:狗汪汪叫
机器人模仿:够快快跑
机器人模仿:鸟儿叽叽叫
机器人模仿:鸟儿快快飞