---
title: "Java的设计模式之一：代理模式"
author: "danielhjd"
date: "2011-06-21T11:52:08Z"
tags: []
categories: ["企业架构"]
slug: "java"
draft: false
lastmod: "2011-06-21T12:10:03Z"
id: 1099549
url: "https://danielhjd.iteye.com/blog/1099549"
---

**代理模式：**

某一个 对象 提供一个 代理对象 ，并由 代理对象 控制对 源对象 的引用。代理就是一个人或一个机构代表另一个或者一个机构采取行动。某些情况下，客户不想或者不能够直接引用一个对象，代理对象可以在客户和目标对象中起 中介的作用。客户端分辨不出代理主题对象与真实主题对象。（客户分辨不出对象的真正所有者是谁）代理模式 可以并不知道真正的 被代理对象，被代理对象必须有系统的其他角色代为创建并传入。

 

代理模式一般涉及到三个角色：

 

抽象角色：

代理角色：

真正角色：

 

代理模式instance:

 

抽象角色： 作为唯一一个购买的对象 RealEstate...

```
package Agency;
	/**
	 *  抽象出房地产的公共属性
	 *  便于Developer进行开发和设计
	 */
public interface RealEstate {
	public int realEstate();
}
```

 开发商：有了RealEstate这个抽象的对象，开发商就可以去实现房地产的开发了，此时RealEstate就有了Developer的特点；房子在哪里 房子的价格等；

```
package Agency;

public class Developer implements RealEstate {
	/**
	 * 实现接口RealEstate
	 * Developer设计自己的房子
	 */

	public int realEstate() {
		System.out.println("Empire Garden Two,DongHu,Wuhan:Opening Celebration June 23,2011");
		return 3000;
	}

}
```

  

开发商要寻找代理来卖他的房子，这时候出现了代理，代理要实现RealEstate接口，才能才能在自己的基础上去对房子进行自己的定位。同时因为代理是买的开发商的房子，所以代理也要将开发商的东西搞过来，这里这里听过构造方法，和实力话一个房子来实现；

```
package Agency;

public class PorxySeller implements RealEstate {
	/**
	 * @parameter RealEstate 
	 */
	RealEstate one;
	
	public PorxySeller(RealEstate  one){
		this.one=one;
	}

	public int realEstate() {
		System.out.println("You sould pay more for this property");
		return one.realEstate()+200;
	}

}
```

 

最后就是客人了，客人首先的看中一个房子 用RealEstate r=new Developer();来实例化出一个，客人还需要一个代理，PorxySeller seller=new PorxySeller(r);通过R将代理和房子联系起来了...

```
package Agency;

public class Client1 {

	public static void main(String[] args) {
		RealEstate r=new Developer();
		PorxySeller seller=new PorxySeller(r);
		System.out.println(seller.realEstate());
	}

}
```

 输出结果：

You sould pay more for this property  
Empire Garden Two,DongHu,Wuhan:Opening Celebration June 23,2011  
3200

![](http://dl.iteye.com/upload/attachment/501892/1ee720fb-5700-3086-8d10-aee3bf00cc3a.jpg)