1.动态代理
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface CRUD{
void add();
void delete();
void insert();
}
class CRUDImpl implements CRUD{
@Override
public void add () {
System.out.println("这是增加的方法");
}
@Override
public void delete () {
System.out.println("这是删除的方法");
}
@Override
public void insert () {
System.out.println("这是插入的方法");
}
}
public class DProxyTest {
public static void main ( String[] args ) {
final CRUDImpl crud = new CRUDImpl();
InvocationHandler handler = new InvocationHandler() {
@Override
public Object invoke ( Object proxy, Method method, Object[] args ) throws Throwable {
System.out.println("检查的方法");
Object invoke = method.invoke(crud, args);
System.out.println("检查完毕的方法");
return invoke;
}
};
CRUD o = (CRUD) Proxy.newProxyInstance(
crud.getClass().getClassLoader(), crud.getClass().getInterfaces(), handler);
o.add();
}
}
2 .静态代理的简单介绍
package com.wcc.proxy;
interface Factory{
void makeCloth();
}
class ProxyFactory implements Factory{
private Factory factory;
public ProxyFactory(Factory factory){
this.factory = factory;
}
@Override
public void makeCloth () {
System.out.println("开始生产衣服");
factory.makeCloth();
System.out.println("生产完毕,请厂长指示");
}
}
class JFXFactory implements Factory{
@Override
public void makeCloth () {
System.out.println("生产了一批花衣服");
}
}
public class Proxytest {
public static void main ( String[] args ) {
JFXFactory factory = new JFXFactory();
ProxyFactory proxyFactory = new ProxyFactory(factory);
proxyFactory.makeCloth();
}
}