Design Pattern 简明教程

Design Patterns - Proxy Pattern

在代理模式中,一个类表示另一个类的功能。这种设计模式属于结构模式。

In proxy pattern, a class represents functionality of another class. This type of design pattern comes under structural pattern.

在代理模式中,我们创建具有原始对象的对象来将其功能作为接口提供给外界。

In proxy pattern, we create object having original object to interface its functionality to outer world.

Implementation

我们将创建一个 Image 接口和实现该 Image 接口的具体类。ProxyImage 是一个代理类,用于减少 RealImage 对象加载的内存占用。

We are going to create an Image interface and concrete classes implementing the Image interface. ProxyImage is a a proxy class to reduce memory footprint of RealImage object loading.

我们的演示类 ProxyPatternDemo 将使用 ProxyImage 来获取 Image 对象,以根据需要加载和显示。

ProxyPatternDemo, our demo class, will use ProxyImage to get an Image object to load and display as it needs.

proxy pattern uml diagram

Step 1

创建一个接口。

Create an interface.

Image.java

public interface Image {
   void display();
}

Step 2

创建实现相同接口的具体类。

Create concrete classes implementing the same interface.

RealImage.java

public class RealImage implements Image {

   private String fileName;

   public RealImage(String fileName){
      this.fileName = fileName;
      loadFromDisk(fileName);
   }

   @Override
   public void display() {
      System.out.println("Displaying " + fileName);
   }

   private void loadFromDisk(String fileName){
      System.out.println("Loading " + fileName);
   }
}

ProxyImage.java

public class ProxyImage implements Image{

   private RealImage realImage;
   private String fileName;

   public ProxyImage(String fileName){
      this.fileName = fileName;
   }

   @Override
   public void display() {
      if(realImage == null){
         realImage = new RealImage(fileName);
      }
      realImage.display();
   }
}

Step 3

根据需要使用 ProxyImage 来获取 RealImage 类的对象。

Use the ProxyImage to get object of RealImage class when required.

ProxyPatternDemo.java

public class ProxyPatternDemo {

   public static void main(String[] args) {
      Image image = new ProxyImage("test_10mb.jpg");

      //image will be loaded from disk
      image.display();
      System.out.println("");

      //image will not be loaded from disk
      image.display();
   }
}

Step 4

验证输出。

Verify the output.

Loading test_10mb.jpg
Displaying test_10mb.jpg

Displaying test_10mb.jpg