Java设计模式——代理模式

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

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

1、创建接口

1
2
3
public interface Image {
   void display();
}

2、创建接口Image的实现类

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
//  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 类的对象

1
2
3
4
5
6
7
8
9
10
11
12
13
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 @   iceriver315  阅读(46)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示