设计模式-适配器模式

在我们平常用的手机充电器,就是一个适配器,它把我们日常使用的交流电通过手机充电器(适配器)转化成手机使用的直流电。

适配器模式Adapter Pattern: (结构型模式)
将一个接口转换为客户希望的另外一个接口,适配器模式使接口不兼容的那些类可以一起工作
适配器别名又叫包装器 Wrapper。

模式中的角色:
1 目标接口(Target):客户所期待的接口。目标可以是具体的或抽象的类,也可以是接口。

2 需要适配的类(Adaptee):需要适配的类或适配者类。

3 适配器(Adapter):通过包装一个需要适配的对象,把原接口转换成目标接口。

示例:
1: 使用继承模式

<?php
/*
使用继承的适配器模式

<?php
class Adapter extends YourClass implements OtherInterface
?>
*/

//已经实现了鲸鱼类
class Whale
{
    public function __construct() {
        $this->name = "Whale";
    }

    public function eatFish() {
        echo "whale eat fish. \n";
    }
}
//已经实现了鲤鱼类
class Carp
{
    public function __construct() {
        $this->name = "Carp";
    }

    public function eatMoss() {
        echo "Carp eat moss. \n";
    }
}


//现在要建一个动物馆
interface Animal
{
    function eatFish();
    function eatMoss();
}

//但是我们不能修改Whale 和 Carp类,于是用Adapter模式
class WhaleAdapter extends Whale implements Animal
{
    public function __construct() {
        $this->name = "Whale";
    }
    public function eatMoss() {
        echo "Whale do not eat moss. \n";
    }
}

class CarpAdapter extends Carp implements Animal
{
    public function __construct() {
        $this->name = "Carp";
    }

    public function eatFish() {
        echo "Carp do not eat moss. \n";
    }
}

$whaleAdpter = new WhaleAdapter();
$whaleAdpter->eatFish();
$whaleAdpter->eatMoss();

$carpAdapter = new CarpAdapter();
$carpAdapter->eatFish();
$carpAdapter->eatMoss();

 

2:使用组件的适配器模式

<?php
/*
使用组件的适配器模式

*/

//已经实现了鲸鱼类
class Whale
{
    public function __construct() {
        $this->name = "Whale";
    }

    public function eatFish() {
        echo "whale eat fish. \n";
    }
}
//已经实现了鲤鱼类
class Carp
{
    public function __construct() {
        $this->name = "Carp";
    }

    public function eatMoss() {
        echo "Carp eat moss. \n";
    }
}

//现在要建一个动物馆
interface Animal 
{
  function eatFish();
  function eatMoss();
}

class WhaleAdapter implements Animal
{
    public function __construct() {
        $this->name = "Whale";
        $this->whale = new Whale();
    }

    public function eatFish() {
        $this->whale->eatFish();
    }

    public function eatMoss() {
        echo "Whale do not eat moss. \n";
    }
}

class CarpAdapter implements Animal
{
    public function __construct() {
        $this->name = "Carp";
        $this->carp = new Carp();
    }

    public function eatFish() {
        echo "Carp do not eat moss. \n";
    }

    public function eatMoss() {
        $this->carp->eatMoss();
    }
}

$whaleAdpter = new WhaleAdapter();
$whaleAdpter->eatFish();
$whaleAdpter->eatMoss();

$carpAdapter = new CarpAdapter();
$carpAdapter->eatFish();
$carpAdapter->eatMoss();

来自:http://csprojectedu.com/2016/03/18/PHPDesignPatterns-10/

posted @ 2017-05-25 21:27  九卷  阅读(213)  评论(0编辑  收藏  举报