代理:
代理(Proxy)是一种设计模式,提供了对目标对象另外的访问方式;即通过代理对象访问目标对象.这样做的好处是:可以在目标对象实现的基础上,增强额外的功能操作,即扩展目标对象的功能.
这里使用到编程中的一个思想:不要随意去修改别人已经写好的代码或者方法,如果需改修改,可以通过代理的方式来扩展该方法
模拟代理图:
静态代理:
代码实现:
首先定义接口------相当于工厂地址和功能
package com.qcby.proxy;
public interface ByClothes {
public void clothes(String size);
}
定义目标对象---制造衣服的工厂
package com.qcby.proxy;
//目标类
public class ClothesFactory implements ByClothes{
@Override
public void clothes(String size) {
// TODO Auto-generated method stub
System.out.print("为您定制一套size为"+size+"的衣服");
}
}
制造代理对象-------代购
package com.qcby.proxy;
public class ProxyClothes implements ByClothes{
private ClothesFactory factory;//目标类型属性
public ProxyClothes(ClothesFactory factory) {
this.factory = factory;
}
/*public ClothesFactory getFactory() {
return factory;
}
public void setFactory(ClothesFactory factory) {
this.factory = factory;
}*/
@Override
public void clothes(String size) {
// 额外的前置服务
FrontService();
factory.clothes(size);
// 额外的后置服务
EndService();
}
//前置服务
public void FrontService() {
System.out.println("售前");
}
//后置服务
public void EndService() {
System.out.println("售后");
}
}
测试:
public class Test {
public static void main(String[] args) {
ClothesFactory clothesFactory = new ClothesFactory();
proxy proxy = new proxy(clothesFactory);
proxy.clothes("S");
}
}
静态代理存在哪些问题?
违反了开闭原则:
程序对访问开放,对修改关闭,换句话来说,当需求发生变化时,我们可以增加新模块来解决新需求,而不是通过改变原来的代码来解决我们的新需求
动态代理:
1.新建接口
package com.qcby.proxy;
public interface Byshoot {
public void shoot(String size);
}
2.新建工厂
package com.qcby.proxy;
public class ShootFactory implements Byshoot{
@Override
public void shoot(String size) {
// TODO Auto-generated method stub
System.out.println("为您定制"+size+"鞋");
}
}
3.新建海外代购公司
package com.qcby.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class QcbyProxy implements InvocationHandler{
//被代理对象
private Object factory;
public Object getFactory() {
return factory;
}
public void setFactory(Object factory) {
this.factory = factory;
}
@Override
public Object invoke(Object proxy, Method method, Object[] arg2) throws Throwable {
// TODO Auto-generated method stub
FrontService();
method.invoke(factory, arg2);//反射思想
EndService();
//后置服务
return null;
}
//前置服务
public void FrontService() {
System.out.println("售前");
}
//后置服务
public void EndService() {
System.out.println("售后");
}
public Object getProxyInstance() {
return Proxy.newProxyInstance(factory.getClass().getClassLoader(), factory.getClass().getInterfaces(), this);
}
}
4.新建测试类---买东西的人
package com.qcby.proxy;
public class Test {
public static void main(String[] args) {
/* ProxyClothes proxy =new ProxyClothes(new ClothesFactory());
proxy.clothes("xxl");*/
//创建代购公司
QcbyProxy qcbyProxy=new QcbyProxy();
ShootFactory shootFactory= new ShootFactory();
qcbyProxy.setFactory(shootFactory);
Byshoot emp1=(Byshoot) qcbyProxy.getProxyInstance();
emp1.shoot("38");
//ClothesFactory clothesFactory=new ClothesFactory();
//qcbyProxy.setFactory(ClothesFactory);
}
}
结果:
代理图示: