动态代理模式Demo


package com.xcl.proxy;

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

//抽象主题角色
interface SaleComputer2 {

public void sale(String typeComputer);
}

// 真实主题角色
class ComputerMaker2 implements SaleComputer2 {

@Override
public void sale(String typeComputer) {
System.out.println("卖出了一台" + typeComputer + "牌子的电脑!!!!");
}
}

// 代理主题角色
class ProxyFactory implements InvocationHandler {

// 包含真实主题角色的引用
private ComputerMaker2 cm = null;

// 前置通知
public void beforAdvice() {
System.out.println("你卖我电脑,我给你85折优惠!!!");
System.out.println("我还送给你一个无线鼠标!!");
}

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String type = (String) args[0];
if (type.equals("联想") || type.equals("三星")) {
if (cm == null) {
cm = new ComputerMaker2();
beforAdvice();// 前置通知
}
method.invoke(cm, type);

afterAdvice();// 后置通知
} else {
exceptionAdvice();// 异常通知
}
return null;
}

public void exceptionAdvice() {
System.out.println("没有你想要的电脑品牌!!!");
}

// 后置通知
public void afterAdvice() {
System.out.println("质量三包,品质有保证!!!");
}

}

// 代理箱
class ComputerProxy2 {

public static SaleComputer2 getComputerMaker() {

ProxyFactory pf = new ProxyFactory();
//第一个参数:代理类的类加载器
//第二个参数:代理类的接口
//第三个参数:代理类
return (SaleComputer2) Proxy.newProxyInstance(ComputerMaker2.class.getClassLoader(), ComputerMaker2.class
.getInterfaces(), pf);
}
}

public class ProxyDemo2 {

public static void main(String[] args) {

SaleComputer2 sc = ComputerProxy2.getComputerMaker();
//sc.sale("联想");
sc.sale("三星");
//sc.sale("dell");
}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值