代理模式

代理模式（proxy pattern），是程式设计中的一种设计模式。所谓的代理者是指一个类别可以作为其它东西的界面。代理者可以作任何东西的界面：网络连接、内存中的大物件、档案或其它昂贵或无法复制的资源。

## 概述

著名的代理模式例子为参照计数（reference counting）指标物件。当一个复杂物件的多份副本须存在时，代理模式可以结合享元模式以减少内存用量。典型作法是建立一个复杂物件及多个代理者，每个代理者会参照到原本的复杂物件。而作用在代理者的运算会转送到原本物件。一旦所有的代理者都不存在时，复杂物件会被移除。

## 结构

<image>

在上面的UML类图中，`Proxy`类实现了`Subject`接口，使它充当`Subject`对象的代替者。它维护一个引用（`realSubject`）至被代替的对象（`RealSubject`），使其可以转发给它（`realSubject.operation()`）。

序列图展示了运行时交互：The `Client`对象通过合作于`Proxy`对象，来控制到`RealSubject`对象的访问。在这个例子中，`Proxy`转发请求至`RealSubject`，它办理这个请求。

## 示例

### C++

下面是C++的例子：

```cpp
import std;

using std::string;
using std::unique_ptr;

// Subject Interface
class Image {
public:
    virtual void display() const = 0;
    virtual ~Image() = default;
};

// Real Subject (expensive to load)
class RealImage : public Image {
private:
    string filename;
public:
    explicit RealImage(const string& file):
        filename{file} {
        loadFromDisk();
    }

    void display() const override {
        std::println("Displaying image: {}", filename);
    }

private:
    void loadFromDisk() const {
        std::println("Loading image from disk: {}", filename);
    }
};

// Proxy (controls access to RealImage)
class ProxyImage : public Image {
private:
    string filename;
    mutable unique_ptr<RealImage> realImage; // lazily created
public:
    explicit ProxyImage(const string& file):
        filename{file} {}

    void display() const override {
        if (!realImage) {
            std::println("(Proxy) Loading image on demand...");
            realImage = std::make_unique<RealImage>(filename);
        }
        realImage->display();
    }
};

// Client code
int main() {
    Image* img = new ProxyImage("photo.png");

    // First display (should load)
    img->display();

    // Second display (should use cached image)
    img->display();

    delete img;
    return 0;
}
```

### Java

以下Java范例解释惰性载入模式中的“虚拟代理”方法。`ProxyImage` 类别用来存取远端方法。

```java
import java.util.*;
 
interface Image {
    public void displayImage();
}

//on System A 
class RealImage implements Image {
    private String filename;
    public RealImage(String filename) { 
        this.filename = filename;
        loadImageFromDisk();
    }

    private void loadImageFromDisk() {
        System.out.println("Loading   " + filename);
    }

    public void displayImage() { 
        System.out.println("Displaying " + filename); 
    }
}

//on System B 
class ProxyImage implements Image {
    private String filename;
    private Image image;
 
    public ProxyImage(String filename) { 
        this.filename = filename; 
    }
    public void displayImage() {
        if(image == null)
              image = new RealImage(filename);
        image.displayImage();
    }
}
 
class ProxyExample {
    public static void main(String[] args) {
        Image image1 = new ProxyImage("HiRes_10MB_Photo1");
        Image image2 = new ProxyImage("HiRes_10MB_Photo2");     
        
        image1.displayImage(); // loading necessary
        image2.displayImage(); // loading necessary
    }
}
```

程式的输出为：

```output
 Loading    HiRes_10MB_Photo1
 Displaying HiRes_10MB_Photo1
 Loading    HiRes_10MB_Photo2
 Displaying HiRes_10MB_Photo2
```

### C#

C#的例子：

```csharp
using System;

namespace Proxy {
    interface IImage {
        void Display();
    }

    class RealImage : IImage {
        public RealImage(string fileName) {
            FileName = fileName;
            LoadFromFile();
        }

        private void LoadFromFile() {
            Console.WriteLine("Loading " + FileName);
        }

        public String FileName { get; private set; }

        public void Display() {
            Console.WriteLine("Displaying " + FileName);
        }
    }

    class ProxyImage : IImage {
        public ProxyImage(string fileName) {
            FileName = fileName;
        }

        public String FileName { get; private set; }

        private IImage image;

        public void Display() {
            if (image == null)
                image = new RealImage(FileName);
            image.Display();
        }
    }
    class Program {
        static void Main(string[] args) {
            IImage image = new ProxyImage("HiRes_Image");
            for (int i = 0; i < 10; i++)
                image.Display();
        }
    }
}
```

程式的输出为：

```output
 Loading HiRes_Image
 Displaying HiRes_Image
 Displaying HiRes_Image
 Displaying HiRes_Image
 Displaying HiRes_Image
 Displaying HiRes_Image
 Displaying HiRes_Image
 Displaying HiRes_Image
 Displaying HiRes_Image
 Displaying HiRes_Image
 Displaying HiRes_Image
```

### Python

下面是Python的上述类似记忆化反向代理的例子：

```python
from abc import ABC, abstractmethod
import functools

class Image(ABC):
    @abstractmethod
    def display(self): pass

@functools.lru_cache(maxsize=2)
class RealImage(Image):
    def __init__(self, filename):
        self.filename = filename
        self.load_from_disk()
    def load_from_disk(self):
        print("Loading    ", self.filename)
    def display(self):
        print("Displaying ", self.filename)

class ProxyImage(Image):
    def __init__(self, filename):
        self.filename = filename
    def display(self):
        RealImage(self.filename).display()

def example():
    image1 = ProxyImage("HiRes_Photo1")
    image2 = ProxyImage("HiRes_Photo2")
    image3 = ProxyImage("HiRes_Photo3")
    image1.display()
    image2.display()
    image3.display()
    image3.display() 
    image2.display()
    image1.display()
```

这里的标准库`functools`的`lru_cache`缓存采用了最少最近使用（LRU）缓存替换算法，缓存的最大大小`maxsize`的缺省值为`128`，如果设置其为`None`，这个缓存就等同于没有大小限制的`cache`缓存，这里为了演示替换效果而将其设置为很小的`2`。下面其执行：

```pycon
>>> example()
Loading     HiRes_Photo1
Displaying  HiRes_Photo1
Loading     HiRes_Photo2
Displaying  HiRes_Photo2
Loading     HiRes_Photo3
Displaying  HiRes_Photo3
Displaying  HiRes_Photo3
Displaying  HiRes_Photo2
Loading     HiRes_Photo1
Displaying  HiRes_Photo1
```

## 外部链接

- Java 中的代理模式
- UML 和 LePUS3 （一种形式塑模语言）中的代理模式
- 以代理模式掌控大局
- PerfectJPattern 开源计划，提供 Java 中代理模式的元件实作。