坦克大战(一期)-设计模式-JDK动态代理

DesignPatterns
bingor 2 years ago
parent b5fc39183d
commit 6b171063a4

@ -0,0 +1,33 @@
package com.msb.proxy.v8;/**
* @Author bingor
* @Date 2022/10/17 10:30
* @Description: com.msb.proxy.v8
* @Version: 1.0
*/
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
*@ClassName LogHandler
*@Description TODO
*@Author bingor
*@Date 2022/10/17 10:30
*@Version 3.0
*/
public class LogHandler implements InvocationHandler {
private Tank tank;
public LogHandler(Tank tank) {
this.tank = tank;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("method " + method.getName() + "start...");
Object o = method.invoke(tank, args);
System.out.println("method " + method.getName() + " end...");
return o;
}
}

@ -0,0 +1,11 @@
package com.msb.proxy.v8;
/**
* @Author bingor
* @Date 2022/10/17 9:40
* @Description: com.msb.proxy.v5
* @Version: 1.0
*/
public interface Movable {
public void move();
}

@ -0,0 +1,38 @@
package com.msb.proxy.v8;/**
* @Author bingor
* @Date 2022/10/17 9:41
* @Description: com.msb.proxy.v5
* @Version: 1.0
*/
import java.lang.reflect.Proxy;
import java.util.Random;
/**
*@ClassName Tank
*@Description TODO
*@Author bingor
*@Date 2022/10/17 9:41
*@Version 3.0
*/
public class Tank implements Movable {
@Override
public void move() {
System.out.println("tank move……");
try {
Thread.sleep(new Random().nextInt(10000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Tank tank = new Tank();
// System.getProperties().put("jdk.proxy.ProxyGenerator.saveGeneratedFiles", "true"); //输出生成的代理类
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true"); //输出生成的代理类
Movable movable = (Movable) Proxy.newProxyInstance(Tank.class.getClassLoader(), new Class[] {Movable.class}, new LogHandler(tank));
movable.move();;
}
}
Loading…
Cancel
Save