静态代理
描述
代理模式可以在不修改被代理对象的基础上,通过扩展代理类,进行一些功能的附加与增强。值得注意的是,代理类和被代理类应该共同实现一个接口,或者是共同继承某个类。为什么叫做静态呢?因为它的类型是事先预定好的
实现
//手机public class Iphone {private String name;private String color;}
//手机的商店的接口public interface Store {Iphone sellPhone();}//手机生产工厂public class AppleStore implements Store{//生产手机public Iphone productPhone() {Iphone iphone = new Iphone();return iphone;}@Overridepublic Iphone sellPhone() {Iphone iphone = this.productPhone();return iphone;}}//代理商店--可以在卖的时候进行一些其他的操作public class ProxyStore implements Store {private AppleStore store = new AppleStore();@Overridepublic Iphone sellPhone() {//得到手机后可以进行其他操作Iphone iphone = this.store.productPhone();System.out.println("我要进行加价了");return iphone;}}
public static void main(String[] args) {Store store = new ProxyStore();Iphone iphone = store.sellPhone();}
动态代理
描述
代替类进行做事情
实现
//要被代理的对象 因为是动态代理不需要在这里面做事情 所以可以是接口public interface AppleStore extends Store {Iphone sellPhone();}
public class ProxyFactory {public static <T> T getStore(Class clazz) {//通过Proxy类创建代理对象//参数1 类加载器 把代理的对象加载进来ClassLoader classLoader = clazz.getClassLoader();//参数2 代理谁--接收的数组Class[] classes = new Class[]{clazz};//参数3 代理对象执行任何方法都会到这个里面来InvocationHandler handler = new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {//参数1 代理对象 参数2 代理的方法 参数3 代理执行时传递的参数Class clazz = method.getDeclaringClass();//判断class 根据不同的class 进行不同的代理return new Iphone();}};T proxy = (T) Proxy.newProxyInstance(classLoader,classes,handler);//将代理出来的对象返回出去return proxy;}}public static void main(String[] args) {Store store = ProxyFactory.getStore(AppleStore.class);Iphone iphone = store.sellPhone();iphone.play();}
