zoukankan      html  css  js  c++  java
  • 代理模式之动态代理

    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    
    
    //接口
    interface MyInterface {
    	public void action();
    }
    
    // 被代理类
    class MyObject implements MyInterface {
    	@Override
    	public void action() {
    		System.out.println("我是被代理类,运行action!

    "); } } //被代理接口 interface ClothFactory{ public void productCloth(); } //被代理类 class NikeClothFactory implements ClothFactory{ @Override public void productCloth() { System.out.println("我是被代理类,Nike 生产衣服"); } } //实现InvocationHandler接口的子类 class MyInvocationhandler implements InvocationHandler { private Object obj; public void setObject(Object obj) { this.obj = obj; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("动态代理类运行,收代理费"); Object returnVal = method.invoke(obj, args); return returnVal; } } //动态代理类 class MyProxy { public static Object getProxyInstance(Object obj, InvocationHandler handler) { return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj .getClass().getInterfaces(), handler); } } public class TestProxy { /** * @Title: main * @Description: * @param: * @return void * @user: wangzg * @Date:2014-10-27 * @throws */ public static void main(String[] args) { // TODO Auto-generated method stub //被代理类 MyObject myObject = new MyObject(); MyInvocationhandler myInvocationhandler = new MyInvocationhandler(); myInvocationhandler.setObject(myObject); Object myProxy = MyProxy.getProxyInstance(myObject, myInvocationhandler); MyInterface myInterface = (MyInterface)myProxy; myInterface.action(); NikeClothFactory nikeClothFactory = new NikeClothFactory(); myInvocationhandler.setObject(nikeClothFactory); Object myProxyNike = MyProxy.getProxyInstance(nikeClothFactory, myInvocationhandler); ClothFactory clothFactory = (ClothFactory)myProxyNike; clothFactory.productCloth(); } }


  • 相关阅读:
    第七天冲刺
    MySQL管理
    LNMP环境搭建
    docker使用笔记
    Laravel5.2使用笔记
    Linux使用笔记
    Redis3.2.11在centos9安装与卸载
    Ubuntu系统
    Linux下安装与卸载PHP
    安装Linux
  • 原文地址:https://www.cnblogs.com/liguangsunls/p/6807593.html
Copyright © 2011-2022 走看看