首頁  >  文章  >  後端開發  >  php設計模式之適配器模式詳解

php設計模式之適配器模式詳解

韦小宝
韦小宝原創
2017-11-15 10:49:521602瀏覽

把對某些相似的類別的操作轉化為一個統一的“接口”(這裡是比喻的說話)--適配器,或者比喻為一個“界面”,統一或屏蔽了那些類的細節。 適配器模式還建構了一種“機制”,使“適應”的類別可以很容易的增減,而不用修改與適配器互動的程式碼,符合“減少程式碼間耦合」的設計原則

php設計模式之適配器模式詳解

<?php
/*
 * 适配器模式
 */
abstract class Toy
{
    public abstract function openMouth();

    public abstract function closeMouth();
}

class Dog extends Toy
{
    public function openMouth()
    {
        echo "Dog open Mouth\n";
    }

    public function closeMouth()
    {
        echo "Dog close Mouth\n";
    }
}

class Cat extends Toy
{
    public function openMouth()
    {
        echo "Cat open Mouth\n";
    }

    public function closeMouth()
    {
        echo "Cat close Mouth\n";
    }
}


//目标角色:红枣遥控公司
interface RedTarget
{
    public function doMouthOpen();

    public function doMouthClose();
}

//目标角色:绿枣遥控公司及
interface GreenTarget
{
    public function operateMouth($type = 0);
}


//类适配器角色:红枣遥控公司
class RedAdapter implements RedTarget
{
    private $adaptee;

    function __construct(Toy $adaptee)
    {
        $this->adaptee = $adaptee;
    }

    //委派调用Adaptee的sampleMethod1方法
    public function doMouthOpen()
    {
        $this->adaptee->openMouth();
    }

    public function doMouthClose()
    {
        $this->adaptee->closeMouth();
    }
}

//类适配器角色:绿枣遥控公司
class GreenAdapter implements GreenTarget
{
    private $adaptee;

    function __construct(Toy $adaptee)
    {
        $this->adaptee = $adaptee;
    }

    //委派调用Adaptee:GreenTarget的operateMouth方法
    public function operateMouth($type = 0)
    {
        if ($type) {
            $this->adaptee->openMouth();
        } else {
            $this->adaptee->closeMouth();
        }
    }
}


class testDriver //客户端,客户想要那种就实现那种
{
    public function run()
    {
        //实例化一只狗玩具
        $adaptee_dog = new Dog();
        echo "没有适配器的普通模式";
        $adaptee_dog->openMouth();
        $adaptee_dog->closeMouth();
        echo "给狗套上红枣适配器\n";
        $adapter_red = new RedAdapter($adaptee_dog);
        //张嘴
        $adapter_red->doMouthOpen();
        //闭嘴
        $adapter_red->doMouthClose();
        echo "给狗套上绿枣适配器\n";
        $adapter_green = new GreenAdapter($adaptee_dog);
        //张嘴
        $adapter_green->operateMouth(1);
        //闭嘴
        $adapter_green->operateMouth(0);
    }
}

$test = new testDriver();
$test->run();

適配器模式將現有介面轉化為客戶類別所期望的接口,實現了對現有類別的複用,它是一種使用頻率非常高的設計模式

相關推薦:

php適配器模式簡介

PHP適配器模式之類適配的程式碼解析

#php適配器模式介紹_PHP教學

以上是php設計模式之適配器模式詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn