java设计模式中的装饰模式和代理模式十分相似,这两种都是类似于Spring的AOP模式,装饰模式偏于在被装饰对象的拓展,代理模式偏于在被代理对象的控制。
1.装饰模式
public interface Sourceable {
public void method();
}
public class Source implements Sourceable {
@Override
public void method() {
System.out.println("the original method!");
}
}
public class Decorator implements Sourceable {
private Sourceable source;
public Decorator(Sourceable source){
super();
this.source = source;
}
@Override
public void method() {
System.out.println("before decorator!");
source.method();
System.out.println("after decorator!");
}
}
public class DecoratorTest {
public static void main(String[] args) {
Sourceable source = new Source();
Sourceable obj = new Decorator(source);
obj.method();
}
}
这里需要注意的是,在DecoratorTest这样的客户端调用Soureable类时,有客户端来创建对象,即被装饰的类对客户端是可见的,客户端可以对其进行一定的操作,这个类被传入装饰类之后我们可以在原有调用方法的基础上,拓展一部分功能。
2.代理模式
public interface Sourceable {
public void method();
}
public class Source implements Sourceable {
@Override
public void method() {
System.out.println("the original method!");
}
}
public class Proxy implements Sourceable {
private Source source;
public Proxy(){
super();
this.source = new Source();
}
@Override
public void method() {
before();
source.method();
atfer();
}
private void atfer() {
System.out.println("after proxy!");
}
private void before() {
System.out.println("before proxy!");
}
}
public class ProxyTest {
public static void main(String[] args) {
Sourceable source = new Proxy();
source.method();
}
}
代理模式更偏向于控制被代理对象,客户端ProxyTest中我本想执行的是被代理对象Source的method方法,但是我需要创建的却是代理对象Proxy,代理对象负责被代理对象的创建和拓展,而整个过成客户端对被代理对象都是不可见的。