PHP设计模式-适配器模式

类图

插座转换

德标接口

interface DBSocketInterface
{
    public function powerWithTwoRound();
}

实现德标的德国插座

class DBSocket implement DBSocketInterface
{
    public function powerWithTwoRound()
    {
        echo "使用两项圆头的插孔供电";
    }
}

德国酒店

class Hotel
{
    private $dbSocket;

    public function setSocket(DBSocketInterface $dbSocket)
    {
        $this->dbSocket = $dbSocket;
    }

    public function charge()
    {
        $this->dbSocket->powerWithTwoRound();
    }
}

国标接口

interface GBSocketInterface
{
    public function powerWithThreeFlat();
}

实现国标的中国插座

class GBSocket
{
    public function powerWithThreeFlat()
    {
        echo "使用三项扁头的插孔供电";
    }
}

适配器(插头转换 接口转换)

class SocketAdatper implements DBSocketInterface
{
    private $gbSocket;

    public function __construct(GBSocketInterface $gbSocket)
    {
        $this->gbSocket = $gbSocket;
    }

    public function powerWithTwoRound()
    {
        $this->gbSocket->powerWithThreeRound;
    }
}

测试

$gbSocket = new GBSocket();
$hotel = new Hotel();
$socketAdapter = new SocketApapter($gbSocket);
$hotel->setSocket($socketApapter);
$hotel->charge();

你可能感兴趣的:(PHP设计模式-适配器模式)