这个模式的理解是:
让代理类做委托类做的事情。
实际上不是代理类做,只是代理类赋值初始化一个委托类来做。
下面是代码结构:
委托类接口
public interface Principal {
public void doSomething();
}
具体的委托实现类
public class PrincipalA implements Principal {
@Override
public void doSomething() {
System.out.println("Principal A can do something.");
}
}
代理类
public class Proxy implements Principal {
private Principal p;
public Proxy(Principal p) {
this.p = p;
}
@Override
public void doSomething() {
p.doSomething();
System.out.println("Proxy cannot do anything. Just let Principal do.");
}
}
调用者
public class ProxyCaller {
public static void main(String[] args) {
PrincipalA pa = new PrincipalA();
Proxy proxy = new Proxy(pa);
proxy.doSomething();
}
}
那么该如何泛型化呢?
关键在于Proxy类。它是来处理所有委托实现类的。
泛型化代码如下:
代理类
@SuppressWarnings("all")
public class Proxy<T extends Principal> {
private T t;
public Proxy(Class<? extends Principal> c) {
try {
t = (T) Class.forName(c.getName()).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
public void execute() {
t.doSomething();
System.out.println("Proxy cannot do anything. Just let Principal do.");
}
}
调用者
public class ProxyCaller {
public static void main(String[] args) {
Proxy<PrincipalA> proxy = new Proxy<PrincipalA>(PrincipalA.class);
proxy.execute();
}
}
就是这样。