设计模式

设计模式 代理模式

2020-06-12  本文已影响0人  Yohann丶blog
WechatIMG37.jpeg

介绍

为其他对象提供一个代理来控制对这个对象的访问,就是给某一对象提供代理对象,并由代理对象控制具体对象的引用。能够协调调用者和被调用者,能够在一定程度上降低系统的耦合性。其特点有耦合性、独立性、安全性。应用在客户访问不到或者被访问者希望隐藏自己,所以通过代理来访问自己。

角色

角色 说明
Subject 抽象主题角色
RealSubject 真实主题角色
Proxy 代理主题角色
Client 访问角色

角色示例

类名 担任角色 说明
Phone Subject 手机
PhoneFactory RealSubject 手机厂家
Agent Proxy 代理商
Customer Client 顾客

UML类图

代理模式.jpg

代码

<?php 
interface Phone
{
    public function sale();
}

class PhoneFactory implements Phone
{
    public function sale()
    {
        return "厂家销售".PHP_EOL;
    }
}

class Agent implements Phone
{
    protected $phoneFactory;
    function __construct()
    {
        $this->phoneFactory = new PhoneFactory();
    }

    public function purchase()
    {
        return "采购".PHP_EOL;
    }

    public function sale()
    {
        return $this->purchase().'代替'.$this->phoneFactory->sale().$this->ship();
    }

    public function ship()
    {
        return "发货".PHP_EOL;
    }
}

class Customer
{
    public $agent;
    function __construct()
    {
        $this->agent = new Agent;
    }
}

$customer = new Customer();
echo $customer->agent->sale();

创建 Agent.php,内容如上。

执行

$ php Agent.php
采购
代替厂家销售
发货
上一篇 下一篇

猜你喜欢

热点阅读