0%

设计模式-代理模式

创建具有现有对象的对象,以便向外界提供功能接口。用于解决直接访问对象时带来的问题

示例

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
interface IImage
{
void Display();
}

public class RealImage : IImage
{
private string fileName;
public RealImage(string fileName)
{
this.fileName = fileName;
LoadFromDisk(fileName);
}
public void Display()
{
//display
}
private void LoadFromDisk(string fileName)
{
//Load Image From Disk
}
}

public class ProxyImage : IImage
{
private RealImage realImage;
private string fileName;
public ProxyImage(string fileName)
{
this.fileName = fileName;
}
public void Display()
{
if(realImage == null)
realImage = new RealImage(fileName);
realImage.Diaplay();
}
}

IImage image = new ProxyImage("test.jpg");
// 图像将从磁盘加载
image.display();
// 图像不需要从磁盘加载
image.display();