代理模式和装饰器模式的区别

区别在于,代理模式,对于被代理的类是固化在代理类中的,而对于装饰器模式,被装饰的类是调用时实例化的,也就是说被装饰的类是可以调用时动态选择的。

比如,代理模式
import java.util.*;
 
interface Image {
    public void displayImage();
}
 
//on System A 
class RealImage implements Image {
    private String filename;
    public RealImage(String filename) { 
        this.filename = filename;
        loadImageFromDisk();
    }
 
    private void loadImageFromDisk() {
        System.out.println("Loading   " + filename);
    }
 
    public void displayImage() { 
        System.out.println("Displaying " + filename); 
    }
}
 
//on System B 
class ProxyImage implements Image {
    private String filename;
    private Image image;
 
    public ProxyImage(String filename) { 
        this.filename = filename; 
    }
    public void displayImage() {
        if(image == null)
              image = new RealImage(filename);
        image.displayImage();
    }
}
 
class ProxyExample {
    public static void main(String[] args) {
        Image image1 = new ProxyImage("HiRes_10MB_Photo1");
        Image image2 = new ProxyImage("HiRes_10MB_Photo2");     
 
        image1.displayImage(); // loading necessary
        image2.displayImage(); // loading necessary
    }
}
注意被代理类初始化化的位置。

而装饰模式如下:
public interface Work
{
  public void insert();

}
public class SquarePeg implements Work{
  public void insert(){
    System.out.println("方形桩插入");
  }

}
public class Decorator implements Work{

  private Work work;
  //额外增加的功能被打包在这个List中
  private ArrayList others = new ArrayList();

  //在构造器中使用组合new方式,引入Work对象;
  public Decorator(Work work)
  {
    this.work=work;
  
    others.add("挖坑");

    others.add("钉木板");
  }

  public void insert(){
    newMethod();
  }


  
  //在新方法中,我们在insert之前增加其他方法,这里次序先后是用户灵活指定的   
  public void newMethod()
  {
    otherMethod();
    work.insert();


  }

  public void otherMethod()
  {
    ListIterator listIterator = others.listIterator();
    while (listIterator.hasNext())
    {
      System.out.println(((String)(listIterator.next())) + " 正在进行");
    }

  }

}
调用的时候
Work squarePeg = new SquarePeg();
Work decorator = new Decorator(squarePeg);
decorator.insert();

请注意被装饰类的初始化位置和方式

猜你喜欢

转载自sailorls.iteye.com/blog/1218758