设计模式(一)------- 代理模式

       许多东西如果概念化,时间久了容易遗忘,所以感觉最好举了例子来。举一反三,能够帮助更好地理解和记忆,甚至于回想。

                                                                                                      ----- 写在前面     

 

       代理模式:

              网上教学,举的例子是坦克(implements Moveable),要记录它的move()时间,等等其他需求。

              举一反三,租房子为例。

                               【 房东(Renter):被代理类; 中介(RenterProxy):代理类】

       目的是将房子租出去(rent())(忽略细节部分,暂且假定houseProxy也有租房子的权利)

       

       Interface: Renter      

 

public interface Renter {
     public void rent();
}

 

 

       Class: HouseOwner

       

public class HouseOwner implements Renter{

	@Override
	public void rent() {
		System.out.println("签订租房合同");
	}

}

 

 

       Class: AgentHandler

       

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class AgentHandler implements InvocationHandler {
	
	private Object target;

	public AgentHandler(Object target) {
		super();
		this.target = target;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		showHouse();
		Object result = method.invoke(target, args);
		afterServe();
		return result;
	}
	
	public void showHouse(){
		System.out.println("Show the house to a tenant.");
	}
	
	public void afterServe(){
		System.out.println("If necessary, serve the tenant.");
	}
	
}

   

 

         Class: 测试类

       

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;


public class AgentTest {
	
	public static void main(String[] args) {
		//房东
		Renter renter = new HouseOwner();
		InvocationHandler h = new AgentHandler(renter);
		//中介
		Renter renterProxy = (Renter)Proxy.newProxyInstance(renter.getClass().getClassLoader(),
		      renter.getClass().getInterfaces(), h);
		//租房成功
		renterProxy.rent();	
	}	
}

 

 

    例子到此告一段落。此为动态代理,即利用反射机制动态生成了代理类。后续:Spring的AOP。

 

                                

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值