php設計模式之Proxy(代理模式)和Facade(外觀)設計模式

來源:互聯網
上載者:User

標籤:

Proxy(代理模式)和Facade(外觀)設計模式
它們均為更複雜的功能提供抽象化的概念,但這兩種實現抽象化的過程大不相同

Proxy案例中,所有的方法和成員變數都來自於目標對象,必要時,該代理能夠對它所傳遞的資料進行修改或檢查
魔術方法使得Proxy的實現變的簡單,Proxy模式的一類應用時用來記錄方法的訪問資訊
還可以利用Proxy的類確定代碼的範圍或偵錯工具中存在的問題

<?phpclass LoggingProxy{    private $target;    //傳遞進去一個對象    public function __construct($target){        $this->target=$target;    }    protected function log($line){        echo "[".$line."]\r\n";    }    public function __set($name,$value){        $this->target->$name=$value;        $this->log("setting value for $name:$value ");    }    public function __get($name){        $value=$this->target->$name;        $this->log("Getting value for $name:$value");        return $value;    }    public function __isset($name){        $value=isset($this->target->$name);        $this->log("checking isset for $name".($value?"true":"false"));        return $value;    }    public function __call($name,$arguments){        $this->log("calling method $name width:".implode(",", $arguments));        return call_user_func_array(array($this->target,$name), $arguments);            }}class People{    public $name=‘hk‘;    public $age;    public function sayname(){        return $this->name;    }    public function plus($a,$b){        return $a+$b;    }}$p=new People();$proxy=new LoggingProxy($p);echo $proxy->name;//hkecho "<br>";$proxy->age=10;echo $p->age;//10echo "<br>";echo $proxy->sayname();echo "<br>";echo $proxy->plus(2,3);

結果

[Getting value for name:hk] hk
[setting value for age:10 ] 10
[calling method sayname width:] hk
[calling method plus width:2,3] 5

多數情況下Proxy不應該改變它所代理的類的行為
Proxy與它所代理的在類型上不完全一致,這也是其一個缺點。
因而若需要進行類型提示或代碼檢查以確保對象是某一特定類型,這種情況下就不能使用代理模式


Facade(外觀)模式提供了不同的功能,用來抽象化複雜功能,以使應用程式無需瞭解子系統處理
各請求的細節,就能完成整個處理過程
例如:處理典型api請求時,使用者需要通過子系統進行認證,認證通過後,請求通過api子系統傳遞給遠程伺服器
處理,最後通過其它api的函數對相應解碼
Facade方法實現如下

<?phpclass Facade{    public function apiRequestJson($method,$parameters){        $user=User::getAuthenticatedUser();        if($user->hasPermission($method)){            $result=$this->api->$method($parameters);            return json_encode($result);        }    }}

Facade並不為子系統添加任何新的功能,而是為子系統委託合適的責任。
子系統無需知道Facade的存在,而應用程式也無需知道子系統的存在。

 

php設計模式之Proxy(代理模式)和Facade(外觀)設計模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.