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");
}
}