孙
孙少平
V1
2022/07/25阅读:7主题:默认主题
静态代理+动态代理
静态代理:
package com.god.se.reflection.proxy;
public class StaticProxyTest {
public static void main(String[] args) {
ClothFactory nikeClothFactory = new NikeClothFactory();
ClothFactory proxyClothFactory = new ProxyClothFactory(nikeClothFactory);
proxyClothFactory.produceCloth();
Star tylor = new Tylor();
Star proxyAgent = new ProxyAgent(tylor);
proxyAgent.sing();
}
}
interface ClothFactory{
void produceCloth();
}
//被代理人
class NikeClothFactory implements ClothFactory{
@Override
public void produceCloth() {
System.out.println("做衣服");
}
}
//代理人
class ProxyClothFactory implements ClothFactory{
private ClothFactory clothFactory;
public ProxyClothFactory(ClothFactory clothFactory){
this.clothFactory=clothFactory;
}
@Override
public void produceCloth() {
System.out.println("准备布料");
clothFactory.produceCloth();
System.out.println("卖衣服");
}
}
interface Star{
void sing();
}
class Tylor implements Star{
@Override
public void sing() {
System.out.println("Tylor is sing....");
}
}
//经纪人:Agent
class ProxyAgent implements Star{
private Star star;
public ProxyAgent(Star star){
this.star=star;
}
@Override
public void sing() {
System.out.println("给Tylor找演出和化妆");
star.sing();
System.out.println("帮Tylor收唱歌的钱,给Tylor叫车");
}
}
动态代理:
package com.god.se.reflection.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class DynamicProxyTest {
public static void main(String[] args) {
HuMan superMan = new SuperMan();
HuMan proxy = (HuMan) ProxyFactory.getProxy(superMan);
proxy.eat();
proxy.getBelief();
Tylor tylor = new Tylor();
Star proxy1 = (Star) ProxyFactory.getProxy(tylor);
proxy1.sing();
}
}
interface HuMan{
void eat();
void getBelief();
}
class SuperMan implements HuMan{
@Override
public void eat() {
System.out.println("superman is eat");
}
@Override
public void getBelief() {
System.out.println("superman's belief is fly ");
}
}
class ProxyFactory{
public static Object getProxy(Object object) {
MyInvocationHandler handler = new MyInvocationHandler();
handler.bind(object);
Object proxyInstance = Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), handler);
return proxyInstance;
}
}
class MyInvocationHandler implements InvocationHandler {
private Object object;
public void bind(Object obj){
this.object=obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("代理开始");
Object returnVal = method.invoke(object, args);
System.out.println("代理结束");
return returnVal;
}
}
作者介绍
孙
孙少平
V1