1、静态代理
接口有几个方法,代理类则实现几个方法,代码冗余。
/** * 接口 * @author YLJ * */ public interface Animal { public void say(); public void sleep(); } /** * 实现类,实现接口,实现方法 * @author YLJ * */ class Dog implements Animal{ @Override public void say() { System.out.println("dog say"); } @Override public void sleep() { System.out.println("dog sleep"); } } /** * 实现类,实现接口,实现方法 * @author YLJ * */ class Cat implements Animal { @Override public void say() { System.out.println("cat say"); } @Override public void sleep() { System.out.println("cay sleep"); } } /** * 代理类,实现接口,实现方法(调用实际角色方法,并添加附加功能) * @author YLJ * */ class Proxy implements Animal { private Animal animal; public Proxy(Animal animal){ this.animal = animal; } @Override public void say() { System.out.println("proxy say..."); animal.say(); } @Override public void sleep() { System.out.println("proxy sleep..."); animal.sleep(); } }
测试
/** * 测试类 * @author YLJ * */ public class App { public static void main(String[] args) { Proxy dog = new Proxy(new Dog()); dog.say(); dog.sleep(); Proxy cat = new Proxy(new Cat()); cat.say(); cat.sleep(); } }
2、动态代理
/** * 接口 * @author YLJ * */ public interface Animal { void say(); void sleep(); } /** * 实现类 * @author YLJ * */ class Dog implements Animal{ private String name; public Dog(String name) { this.name = name; } public void say(){ System.out.println(this.name + ": say。。。"); } public void sleep() { System.out.println(this.name + ": say。。。"); } } /** * 实现类 * @author YLJ * */ class Cat implements Animal{ private String name; public Cat(String name) { this.name = name; } public void say(){ System.out.println(this.name + ": say。。。"); } public void sleep() { System.out.println(this.name + ": say。。。"); } } class AnimalHandler implements InvocationHandler{ private Animal animal; public AnimalHandler(Animal animal) { this.animal = animal; } /** * 核心方法,实现所有代理方法调用, */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("proxy..."); method.invoke(animal, args); return null; } }
测试
public static void main(String[] args) { Animal dog = new Dog("旺财"); AnimalHandler dogHandler = new AnimalHandler(dog); Animal d = (Animal)Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{Animal.class}, dogHandler); d.say(); d.sleep(); Animal cat = new Dog("猫咪"); AnimalHandler catHandler = new AnimalHandler(cat); Animal c = (Animal)Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{Animal.class}, catHandler); c.say(); c.sleep(); }