php设计模式2

<?php /** * 代理模式:为其他对象提供一个代理以控制这个对象的访问 它是给某一个对象提供一个替代者,使之在client对象和subject对象之间编码更有效率。 代理可以提供延迟实例化,控制访问等 应用场景:如果需要创建一个资源消耗较大的对象,先创建一个消耗相对较小的对象来表示,真实对象只在需要时才会被真正创建。 控制对原始对象的访问。 * */ /** * 抽象主题角色(Subject):天气 * */ interface Weather { public function request($city); public function display($city); public function isValidCity($city); } /** * 真实主题角色(RealSubject): * */ class RealWeather implements Weather { protected $_url = \'http://www.google.com/ig/api?&oe=utf-8&hl=zh-cn&weather=\'; protected $_weatherXml = \'\' ; function __construct(){ } public function request($city){ $this->_weatherXml = file_get_contents($this->_url . $city ); } public function display($city ){ // if ($this->_weatherXml == \'\') { // $this->request($city); // } echo \'天气预报\'; } public function isValidCity($city){ } } /** * 代理角色(Proxy):延迟代理 * */ class ProxyWeather implements Weather { private $_client ; private function client() { if (! $this->_client instanceof RealWeather) { $this->_client = new RealWeather(); } return $this->_client; } public function request($city){ $this->_client->request($city); } public function isValidCity($city) { return $this->_client->isValidCity($city); } public function display($city) { return $this->client()->display($city); } } /** * 代理角色(Proxy):动态代理 * */ class DynamicProxyWeather { protected $_subject; public function __construct($subject) { $this->_subject = $subject; } public function __call($method, $args) { return call_user_func_array([$this->_subject, $method], $args); } } // 客户端 class Client{ public static function proxy(){ $proxy = new ProxyWeather(); $proxy->display(\'beijing\'); } public static function dynamic(){ $proxy = new DynamicProxyWeather(new RealWeather()); $proxy->display(\'beijing\'); } } Client::proxy(); Client::dynamic();

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwpdxw.html