Java设计模式——代理模式

代理模式是一种结构模式,可以简单理解成一个类代表另外一个类的功能。跟适配器模式有一点像。

举例说明:创建一个接口Image,以及它的实现类 RealImage、ProxyImage;ProxyImage是一个代理类,用于减少RealImage类加载时候的内存占用。

1、创建接口

public interface Image {
   void display();
}

2、创建接口Image的实现类

//  RealImage
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
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();
   }
}

3、使用 ProxyImage 获取 RealImage 类的对象

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(); 	
   }
}

4、测试结果

Loading test_10mb.jpg
Displaying test_10mb.jpg

Displaying test_10mb.jpg

 

posted @ 2022-04-05 22:05  iceriver315  阅读(42)  评论(0编辑  收藏  举报