设计模式-代理
作者:edwin
日期:2019-08-05 14:47:00
所属分类:后端 - php

代理这种模式提供了一个代理或占位符为另一个对象来控制对它的访问

Proxy(代理)
This class (a) maintains a reference that lets the proxy access the real subject, (b) provides an interface identical(完全相同的) to Subject's so that a proxy can be substituted(['sʌbstitju:tid] 代替) for the real subject, and (c) controls access to the real subject and may be responsible for creating and deleting it.
(这类(a)维护一个引用,让代理访问真正的主题,(b)给主题提供一个完全相同的接口,让一个代理可以代替真正的主题,和(c)控制访问真正的主题,能够负责创建和删除它。)

RealSubject(真对象)
This class defines the real object that the proxy represents.
(这个类定义了真正的对象,代理所代表的。)

Subject(主题)
This class defines the common interface for RealSubject and Proxy so that a Proxy can be used anywhere a RealSubject is expected(预期).
(这个类为真正地主题和代理定义了共同的接口,一个真正地主题被预期的地方都能使用代理。)

代码实现

<?php

class Proxy extends Subject
{
    private $_subject = null;
    public function __construct() {
        $this->_subject = new RealSubject();
    }

    public function request() {
        $this->_subject->request();
    }

    public function display() {
        $this->_subject->display();
    }
}

class RealSubject extends Subject
{
    public function request() {
        echo "RealSubject request <br/>";
    }

    public function display() {
        echo "RealSubject display <br/>";
    }
}

interface Subject
{
    public function request();
    public function display();
}

$objProxy = new Proxy();
$objProxy->request();
$objProxy->display();

评论

全部评论 / 0