两者本质区别: 装饰模式是为所装饰的对象增强功能;
而代理模式对代理的对象施加控制,但不对对象本身的功能进行增强;
public interface Greeting {
void sayHello(String name);
}
public class GreetingImpl implements Greeting {
@Override
public void sayHello(String name) {
System.out.println("Hello! " + name);
}
可以使用 Proxy 类来代理 GreetingImpl 类做点事情:
public class GreetingProxy implements Greeting {
private GreetingImpl greetingImpl;
public GreetingProxy(GreetingImpl greetingImpl) {
this.greetingImpl = greetingImpl;
}
@Override
public void sayHello(String name) {
before();
greetingImpl.sayHello(name);
}
private void before() {
System.out.println("Before");
}
}