---
title: "代理模式的UML类图与实现源码"
author: "hlzhou"
date: "2009-12-18T16:33:22Z"
tags: ["UML", "thread"]
categories: ["企业架构"]
slug: "uml"
draft: false
lastmod: "2009-12-18T18:19:45Z"
id: 551507
url: "https://hlzhou.iteye.com/blog/551507"
---

以下是一个代理模式的UML图：

![](http://dl.iteye.com/upload/attachment/182475/ae86ee13-89fd-326f-969a-754faf9a162e.png)

源码：Image接口

 

```
public interface Image {
 void show();
}
```

 BigImage类

 

```
public class BigImage implements Image {
	public BigImage(){
		try {
//系统延时3秒用来模拟调用大图片时有系统延时
			Thread.sleep(3000);
			System.out.println("Image Successfully loaded.");
		} catch (InterruptedException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	public void show() {
		System.out.println("Draw Real Image");
	}
}
```

 

 ImageProxy类

 

```
public class ImageProxy implements Image {

	private Image image;
	public ImageProxy(Image image){
		this.image=image;
	}
	
	public void show() {
		if(image==null){
			image=new BigImage();
		}
		image.show();
	}
}
```

 

 

 

BigImageTest类(客户端)

 

```
public class BigImageTest {

	public static void main(String[] args) {
		System.out.println("使用代理");
               //null,确保每次调用show方法需要示例化BigImage
		Image image=new ImageProxy(null);
		System.out.println("开始显示图片");
		image.show();
		System.out.println("***************************************");
		System.out.println("没使用代理");
		Image image2=new BigImage();
		image2.show();
	}
}
```