静态代理

目录

代理

不使用代理案例

静态代理案例


代理

java的代理都是基于接口实现的,代理使得原本不具有某种行为的类在不修改源码的情况下具有某种行为能力。

静态代理:只能代理某一类型的接口的实例。不能做到任何类任何方法的代理。

不使用代理案例

/**
一些公共操作的逻辑都需要自己在每个方法里单独写一遍
*/
//接口
public interface MapperInterface {
    void save(User user);
}
//实现类1
public class StudentMapper implements MapperInterface{
    @Override
    public void save(User user) {
        System.out.println("建立连接");
        System.out.println("保存student");
        System.out.println("提交事务");
        System.out.println("断开连接");
    }
}
//实现类2
public class UserMapper implements MapperInterface {
    @Override
    public void save(User user) {
        System.out.println("建立连接");
        System.out.println("保存user");
        System.out.println("提交事务");
        System.out.println("断开连接");
    }
}


静态代理案例

/**
上面的案例: 实现同一个接口的类有好多公共的代码每次都写一遍很麻烦又没有技术含量。
这样的公共的事情可以让代理去实现。本类只需要写核心代码即可
*/

//实现类1
public class StudentMapper implements MapperInterface {
    @Override
    public void save(User user) {
        System.out.println("保存student");
    }
}
//实现类2
public class UserMapper implements MapperInterface {
    @Override
    public void save(User user) {
        System.out.println("保存user");
    }
}
/**静态代理类(把公共的处理逻辑放在代理里面,代理通过构造方法传入被代理的对象(从而掌握了它),
可以随时调用其中的方法),就可以在其前其后做一些公共的逻辑
*/
public class StaticProxy {
    MapperInterface mapperInterface;

    public StaticProxy(MapperInterface mapperInterface) {
        this.mapperInterface = mapperInterface;
    }

    public String save(User user) {
        System.out.println("建立连接");
        this.mapperInterface.save(user);
        System.out.println("提交事务");
        System.out.println("断开连接");
        return user.getUserName();
    }
}
//测试
public class TestStaticProxy {
    @Test
    public void test() {
        StaticProxy staticProxy = new StaticProxy(new UserMapper());
        staticProxy.save(new User());
    }
}

测试结果:

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值