结构型 - 代理(Proxy)

arcstack2023年5月26日约 728 字大约 2 分钟

结构型 - 代理(Proxy)

代理模式(Proxy pattern): 为另一个对象提供一个替身或占位符以控制对这个对象的访问。@pdai

意图

控制对其它对象的访问。

类图

代理有以下四类:

a6c20f60-5eba-427d-9413-352ada4b40fe.png
a6c20f60-5eba-427d-9413-352ada4b40fe.png

实现

以下是一个虚拟代理的实现,模拟了图片延迟加载的情况下使用与图片大小相等的临时内容去替换原始图片,直到图片加载完成才将图片显示出来。

    public interface Image {
        void showImage();
    }

    public class HighResolutionImage implements Image {

        private URL imageURL;
        private long startTime;
        private int height;
        private int width;

        public int getHeight() {
            return height;
        }

        public int getWidth() {
            return width;
        }

        public HighResolutionImage(URL imageURL) {
            this.imageURL = imageURL;
            this.startTime = System.currentTimeMillis();
            this.width = 600;
            this.height = 600;
        }

        public boolean isLoad() {
            // 模拟图片加载,延迟 3s 加载完成
            long endTime = System.currentTimeMillis();
            return endTime - startTime > 3000;
        }

        @Override
        public void showImage() {
            System.out.println("Real Image: " + imageURL);
        }
    }

    public class ImageProxy implements Image {
        private HighResolutionImage highResolutionImage;

        public ImageProxy(HighResolutionImage highResolutionImage) {
            this.highResolutionImage = highResolutionImage;
        }

        @Override
        public void showImage() {
            while (!highResolutionImage.isLoad()) {
                try {
                    System.out.println("Temp Image: " + highResolutionImage.getWidth() + " " + highResolutionImage.getHeight());
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            highResolutionImage.showImage();
        }
    }

    public class ImageViewer {
        public static void main(String[] args) throws Exception {
            String image = "http://image.jpg";
            URL url = new URL(image);
            HighResolutionImage highResolutionImage = new HighResolutionImage(url);
            ImageProxy imageProxy = new ImageProxy(highResolutionImage);
            imageProxy.showImage();
        }
    }

JDK

参考资料