Heim  >  Artikel  >  Backend-Entwicklung  >  php设计模式-代理模式

php设计模式-代理模式

WBOY
WBOYOriginal
2016-06-20 12:25:39793Durchsuche

代理模式定义

为其他对象提供一种代理以控制对这个对象的访问。在某些情况下,一个对象不适合或者不能直接引用另一个对象,而代理对象可以在客户端和目标对象之间起到中介的作用

主要角色

抽象角色:通过接口或抽象类声明真实角色实现的业务方法。

代理角色:实现抽象角色,是真实角色的代理,通过真实角色的业务逻辑方法来实现抽象方法,并可以附加自己的操作。

真实角色:实现抽象角色,定义真实角色所要实现的业务逻辑,供代理角色调用。

优点

职责清晰

代理对象可以在客户端和目标对象之间起到中介的作用,这样起到了中介的作用和保护了目标对象的作用。

高扩展性

代理模式实例

<?php  //抽象角色interface IGiveGift  {      function giveRose();      function giveChocolate();  }    //真实角色class Follower implements IGiveGift  {      private $girlName;        function __construct($name='Girl')      {          $this->girlName=$name;      }        function giveRose()      {          echo "{$this->girlName}:送你的玫瑰<br/>";      }        function giveChocolate()      {          echo "{$this->girlName}:送你的巧克力<br/>";      }  }    //代理角色class Proxy implements IGiveGift  {      private $follower;        function __construct($name='Girl')      {          $this->follower=new Follower($name);      }        function giveRose()      {          $this->follower->giveRose();      }        function giveChocolate()      {          $this->follower->giveChocolate();      }  }$proxy=new Proxy('xxx');  $proxy->giveRose();  $proxy->giveChocolate();
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn