PHP设计模式中的代理模式(Proxy),它是对简单处理程序(或指针)的增强,用于引用一个对象:这个指针被代理(Proxy)对象取代,代理对象位于客户端(Client)和真实执行程序之间,指针有一个可被多个目标利用的钩子。
从技术上讲,这种模式在客户端和真实主体(RealSubject)之间插入一个代理对象,维护subject接口和用不同的方式委派它的方法。
参与者:
◆客户端(Client):取决于主体(Subject)实现;
◆主体(Subject):RealSubject的抽象;
◆真实主体(RealSubject):完成代价高昂的工作或包含大量的数据;
◆代理(Proxy):为Client提供一个与Subject一致的引用,仅在需要时才创建RealSubject实例或与RealSubject实例通信。
广泛使用的代理模式例子:
1、对象-关系映射(Orms)在运行中创建代理作为实体类的子类,以实现懒散加载(虚拟代理),这个代理会覆盖所有实体方法,在前面追加一个载入程序,在方法被真正调用前不会包含任何数据,Orms代理支持对象间的双向关系,不用加载整个数据库,因为它们被置于当前加载对象图的边界。
感觉好难理解吧,我也不是很理解,看代码吧~~~回头慢慢理解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
<?php
//定义接口
interface
Image {
public
function
getWidth();
public
function
getHeight();
public
function
getPath();
//返回图片内容
public
function
dump();
}
//抽象类主要是为了代码层次,防止重复引用吧
abstract
class
AbstractImage
implements
Image{
protected
$_width
;
protected
$_height
;
protected
$_path
;
protected
$_data
;
public
function
getWidth(){
return
$this
->_width;
}
public
function
getHeight(){
return
$this
->_height;
}
public
function
getPath(){
return
$this
->_path;
}
}
//真实主体
class
RawImage
extends
AbstractImage{
public
function
__construct(
$path
){
$this
->_path =
$path
;
list(
$this
->_width,
$this
->_height) =
getimagesize
(
$path
);
$this
->_data =
file_get_contents
(
$path
);
}
public
function
dump(){
return
$this
->_data;
}
}
//代理
class
ImageProxy
extends
AbstractImage{
public
function
__construct(
$path
) {
$this
->_path =
$path
;
list(
$this
->_width,
$this
->_height) =
getimagesize
(
$path
);
}
protected
function
_layzLoad(){
if
(
$this
->_realImage === null) {
$this
->_realImage =
new
RawImage(
$this
->_path);
}
}
public
function
dump(){
$this
->_layzLoad();
return
$this
->_realImage->dump();
}
}
//Client类比没有使用_data来输出image
class
Client{
public
function
tag(Image
$img
){
return
;
}
}
$path
=
'/home/jane/下载/0904190.jpg'
;
$client
=
new
Client();
//_data数据会被加载
$image
=
new
RawImage(
$path
);
echo
$client
->tag(
$image
);
//_data数据不会被加载
$proxy
=
new
ImageProxy(
$path
);
echo
$client
->tag(
$proxy
);
|
本文转自shayang8851CTO博客,原文链接:http://blog.51cto.com/janephp/1346236
,如需转载请自行联系原作者