代理模式

学习spring 之前java中的几个模式是很重要的 其中一个就是代理模式。下面用几个简单的例子来理解一下这个模式。以及它的应用。

1,普通的代理模式。


class House{
    
private float price=200f;

    
public float getPrice(){
        
return price;
    }

    
    
public void  setPrice(){
        
this.price = price;
    }

}

//房东
class  HouseOwner{
    House house 
= null;
    
    HouseOwner(House house)
{
        
this.house = house;
    }
    
    
    
public void rent(){
        System.out.println (
"房东出租房子价格是:"+house.getPrice());
    }

}



//中介商
class  HouseProxy {
    
//20% 的中介费
    float centPricePoint = 0.2f;
    
    HouseOwner own 
= null;
    
    
    HouseProxy (HouseOwner own)
{
         
this.own = own;
    }

    
    
public void rent(){
        
        
//调用真实的方法前做一些事
        System.out.println ("收取中介费"+own.house.getPrice()*centPricePoint);
        
        own.rent();
        
        
//调用真实的方法后做一些事
        System.out.println ("交易成功。");
    
    }

    
    
    
}

//客户
class Rentor {
    
public static void main(String[] args){
        House h 
= new House();
        
        
//客户找房东
        HouseOwner o = new HouseOwner(h);
        o.rent();
        
        
        System.out.println (
"*******************");
        
        
//客户找代理
        HouseProxy hp = new HouseProxy(o);
        hp.rent();
    }

}

//通过代理我们可以屏蔽掉对象的真实方法的实现。来添加自己相关的业务逻辑。

2,动态代理模式。

//假设做一个ArrayList 的 添加提示的功能。 就是 在调用它的add方法的时候 输出一句 请检查类型.

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.*;
import java.util.*;
class ArrayListProxy implements  InvocationHandler{
    Object list ;
    
    ArrayListProxy(Object list )
{
        
this.list  = list;
    }

    
    
    
public Object invoke(Object proxy, Method method, Object[] args)
        
throws Throwable{
        
        
if(method.getName().equals("add")){
            
//对特定方法代理
            System.out.println ("请检查类型.......befor:"+method.getName());
        }

        
        
//对所有方法代理
        
//System.out.println ("请检查类型.......befor:"+method.getName());
        Object o =  method.invoke(list,args);
        
        
return o ;
        
    }

    
    
    
public static Object factory(Object o ){
        Class c 
= o.getClass();
        
        
//用真实的对象来构造代理对象
        return Proxy.newProxyInstance(c.getClassLoader(),c.getInterfaces(),new ArrayListProxy(o));
    }

}


class TestDProxy{
    
public static void main(String[] args){
        ArrayList al 
= new ArrayList();
        List pro 
=  (List)ArrayListProxy.factory(al);
        
        
        pro.add(
"aaa");
        System.out.println (pro.size());
        
        
        
    }

}

通过代理我们屏蔽了真实对象的实现 。理解这个模式后才能更好的理解 AOP

原文地址:https://www.cnblogs.com/yefengmeander/p/2887889.html