Proxy Pattern
- Act as an interface for something else
- Interface based
- Create an interface
public interface TwitterService {
public String getTimeline();
}
- Create the implementation(s)
public class TwitterServiceStub implements TwitterService {
@Override
public String getTimeline() {
return "Printing Timeline --...";
}
}
- Create the Proxy
- that implements InvocationHandler that works by reflection
public class SecurityProxy implements InvocationHandler {
Object obj;
private SecurityProxy(Object obj) {
this.obj = obj;
}
public static Object newInstance(Object obj) {
return java.lang.reflect.Proxy.newProxyInstance(obj.getClass().
getClassLoader(), obj.getClass().getInterfaces(), new SecurityProxy(obj));
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result;
try {
- You can add security adding
- if( method.getName.contains (" remove" )){
- //... don't performe an action
- }
result = method.invoke(obj, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
} catch (Exception e) {
throw new RuntimeException("Unexpected expection: " + e.getMessage());
}
return result;
}
}
Comentarios
Publicar un comentario