代理模式

静态代理

  • 真实角色
  • 代理角色 :持有真实角色的引用
  • 二者实现相同的接口

最近在北京租房,举一个租房的例子

创建一个租房的接口,里面有租房方法

public interface Rent{
    //公共方法租房
    void renting();
}

真实角色

class You implements Rent{
    @Override
    //租房
    public void renting(){
        System.out.println("我要租房子");
    }
}

代理角色,中介公司

class Agency implements Rent{
    Rent you;
    public Agency(){

    }
    public Agency(Rent you){
        this.you = you;
    }
    //租房前要做的
    private void before(){
        System.out.println("找中介公司");
    }
    private void after(){
        System.out.println("交房租");
    }
    @Override
    public void renting(){
        before();
        you.renting();
        after();
    }
}

测试

public class StaticProxy {
    public static void main(String[] args) {
        //创建真实角色
        You you = new You();
        //创建代理角色+真实角色的引用
        Agency agency = new Agency(you);
        agency.renting();
    }
}
输出:
找中介公司
我要租房子
交房租

动态代理

使用java.lang.reflect.Proxy实现

Rent接口

public interface Rent {
    public void renting();
}

真实角色

public class You implements Rent {
    public void renting() {
        System.out.println("我要租房子");
    }
}

代理角色,中介公司

public class ProxyHandler implements InvocationHandler{

    private Object tar;
    //绑定委托对象,并返回代理类
    public Object bind(Object tar){
        this.tar = tar;
        //绑定该类实现的所有接口,取得代理类
        return Proxy.newProxyInstance(tar.getClass().getClassLoader(),
                           tar.getClass().getInterfaces(),
                this);
    }
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = null;
        //这里可以进行AOP编程
        //在调用具体函数方法前,执行功能处理
        System.out.println("找中介公司");
        result = method.invoke(tar,args);
        //在调用具体函数方法后,执行功能处理
        System.out.println("交房租");
        return result;
    }
}

测试

public class TestProxy {
    public static void main(String[] args) {
        ProxyHandler proxyHandler = new ProxyHandler();
        Rent rent = (Rent) proxyHandler.bind(new You());
        rent.renting();
    }
}

输出:
找中介公司
我要租房子
交房租
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值