【设计模式】静态代理与动态代理详解

静态代理

截图来自《大话设计模式》

// 定义接口
public interface Rent {
    public void rent();
}

// 目标类
public class Host implements Rent{
    public void rent() {
        System.out.println("房东出租房子!");
    }
}

// proxy
public class Proxy implements Rent {

    // 真实角色,若有多个真实角色,则需要些多个对应的静态代理类
    private Host host;
    public Proxy(Host host) {
        this.host = host;
    }

    public void rent() {
        find();
        transaction();
        host.rent();
        find();
    }

    public void find() {
        System.out.println("代理找房源中...");
    }

    public void transaction() {
        System.out.println("缴纳定金,继续交易!");
    }

    public void finish() {
        System.out.println("完成交易!");
    }
}

// client
public class Client {
    public static void main(String[] args) {
        Host host = new Host();
        Proxy proxy = new Proxy(host);
        proxy.rent();
    }
}

动态代理

public interface UserService {
    public void add();
    public void query();
}

public class UserServiceImpl implements UserService {
    public void add() {
        System.out.println("添加数据成功!");
    }
    public void query() {
        System.out.println("查询数据完成!");
    }
}

public class MyInvocationHandler implements InvocationHandler {

    private Object target;

    // 设置被代理的实体
    public void setTarget(Object o) {
        target = o;
    }

    // 获取代理实例
    public Object getProxy() {
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        log(method.getName());
        Object invoke = method.invoke(target, args);
        return invoke;
    }

    public void log(String msg) {
        System.out.println("log info:" + msg +" success!");
    }

}

public class Client {
    public static void main(String[] args) {
        // 真实角色
        UserServiceImpl userService = new UserServiceImpl();
        // 代理角色,不存在
        MyInvocationHandler mih = new MyInvocationHandler();
        // 设置被代理的对象
        mih.setTarget(userService);
        // 动态生成代理类
        UserService proxy = (UserService) mih.getProxy();
        proxy.add();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值