代理模式

来源:互联网 发布:网络电影发展史 编辑:程序博客网 时间:2024/06/13 01:53

代理模式(Proxy Pattern)属于结构型模式,在程序中添加中间层,为象提供代理来控制对对象的访问。这种模式解决了直接访问对象带来的问题,例如买火车票不一定在火车站买,也可以去代售点,更加方便。例如,直接访问有些对象会产生很大的开销,我们可以加个代理层,节约性能。等等。

demo:

图像接口:

public interface Image {    void display();}

真正的图像处理类:

public class RealImage implements Image {    private String fileName;    // 初始化图片的时候就从磁盘中加载图片    public RealImage(String fileName) {        this.fileName = fileName;        loadFromDisk();    }    private void loadFromDisk() {        System.out.println("Loading Form Disk" + fileName);    }    @Override    public void display() {        System.out.println("Displaying " + fileName);    }}

代理显示图片的类:

public class ProxyImage implements Image {    private RealImage realImage;    private String fileName;    public ProxyImage(String fileName) {        this.fileName = fileName;    }    @Override    public void display() {        // 显示图片        if (realImage == null) {            realImage = new RealImage(fileName);        }        realImage.display();    }}

调用:

Image image = new ProxyImage("momo.jpg");  // 从硬盘中加载图片image.display();    // 显示图片image.display();    // 显示图片
原创粉丝点击