設計模式之代理模式,裝飾模式和繼承
阿新 • • 發佈:2019-01-24
// 抽象角色(之前是抽象類,此處應改為介面):
public interface Subject {
abstract public void request();
}
// 具體角色RealSubject:
public class RealSubject implements Subject {
public RealSubject() {}
public void request() {
System.out.println( " From real subject. " );
}
}
// 代理處理器:
import java.lang.reflect.Method;
import java.lang.reflect.InvocationHandler;
public class DynamicSubject implements InvocationHandler {
private Object sub;
public DynamicSubject() {}
public DynamicSubject(Object obj) {
sub = obj;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println( " before calling " + method);
method.invoke(sub,args);
System.out.println( " after calling " + method);
return null ;
}
}
public interface Subject {
abstract public void request();
}
// 具體角色RealSubject:
public class RealSubject implements Subject {
public RealSubject() {}
public void request() {
System.out.println( " From real subject. " );
}
}
// 代理處理器:
import java.lang.reflect.Method;
import
public class DynamicSubject implements InvocationHandler {
private Object sub;
public DynamicSubject() {}
public DynamicSubject(Object obj) {
sub = obj;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println( " before calling "
method.invoke(sub,args);
System.out.println( " after calling " + method);
return null ;
}
}