动态代理与AOP

来源:互联网 发布:hdmi能传输数据么 编辑:程序博客网 时间:2024/05/19 04:03
interface Human {void info();void fly();}// 被代理类class SuperMan implements Human {public void info() {System.out.println("我是超人!我怕谁!");}public void fly() {System.out.println("I believe I can fly!");}}class HumanUtil {public void method1() {System.out.println("=======方法一=======");}public void method2() {System.out.println("=======方法二=======");}}class MyInvocationHandler implements InvocationHandler {Object obj;// 被代理类对象的声明public void setObject(Object obj) {this.obj = obj;}@Overridepublic Object invoke(Object proxy, Method method, Object[] args)throws Throwable {HumanUtil h = new HumanUtil();h.method1();Object returnVal = method.invoke(obj, args);h.method2();return returnVal;}}class MyProxy {// 动态的创建一个代理类的对象public static Object getProxyInstance(Object obj) {MyInvocationHandler handler = new MyInvocationHandler();handler.setObject(obj);return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), handler);}}public class TestAOP {public static void main(String[] args) {SuperMan man = new SuperMan();//创建一个被代理类的对象Object obj = MyProxy.getProxyInstance(man);//返回一个代理类的对象Human hu = (Human)obj;hu.info();//通过代理类的对象调用重写的抽象方法System.out.println();hu.fly();//*********NikeClothFactory nike = new NikeClothFactory();Object obj1 = MyProxy.getProxyInstance(nike);ClothFactory cloth = (ClothFactory)obj1;cloth.productCloth();}}



//静态代理模式//接口interface ClothFactory{void productCloth();}//被代理类class NikeClothFactory implements ClothFactory{@Overridepublic void productCloth() {System.out.println("Nike工厂生产一批衣服");}}//代理类class ProxyFactory implements ClothFactory{ClothFactory cf;//创建代理类的对象时,实际传入一个被代理类的对象public ProxyFactory(ClothFactory cf){this.cf = cf;}@Overridepublic void productCloth() {System.out.println("代理类开始执行,收代理费$1000");cf.productCloth();}}public class TestClothProduct {public static void main(String[] args) {NikeClothFactory nike = new NikeClothFactory();//创建被代理类的对象ProxyFactory proxy = new ProxyFactory(nike);//创建代理类的对象proxy.productCloth();}}


0 0