美文网首页
PHP设计模式-适配器模式

PHP设计模式-适配器模式

作者: spike15 | 来源:发表于2016-04-23 21:15 被阅读0次

    类图

    插座转换

    德标接口

    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设计模式-适配器模式

          本文链接:https://www.haomeiwen.com/subject/ckffrttx.html